36. Valid Sudoku

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.


A partially filled sudoku which is valid.

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

分析

就是对横向,纵向,以及子方格进行验证,保证出现的1-9这些数字没有重复;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        bool rv[9][9] = {false}, cv[9][9] = {false}, sv[9][9] = {false};
        for(int i = 0; i < 9; ++i){
            for(int j = 0; j < 9; ++j){
                if(board[i][j] != '.'){
                    int p = board[i][j] - '0' - 1, k = i/3 * 3 + j/3;
                    if(rv[i][p] || cv[p][j] || sv[k][p]){
                        return false;
                    }
                    rv[i][p] = cv[p][j] = sv[k][p] = true;
                }
            }
        }
        return true;
    }
};




原文地址:https://www.cnblogs.com/zhxshseu/p/79ac61dc4f71fa83e27389eb8f5dd215.html