LeetCode#36. Valid Sudoku

  • 题目:判断该方格是否为有效的数独
  • 难度:Medium
  • 思路:数独需要满足行、列、宫出现的数字不重复。定义三个bool类型的二维数组,分别判断行列宫是否满足条件。
  • 代码:
class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        bool row[9][9]  = {false};//检查行
        bool col[9][9]  = {false};//检查列
        bool block[9][9]  = {false};//检查block

        for (int i = 0; i < board.size(); i++) {

            for(int j = 0; j < board[0].size(); j++) {

                if(board[i][j] != '.'){
                    int num = board[i][j] - '0' - 1;
                    int k = i/3*3 + j/3;
                    if(row[i][num] || col[j][num] || block[k][num]){
                        return false;
                    }else{
                        row[i][num] = true;
                        col[j][num] = true;
                        block[k][num] = true;
                    }
                }
            }
        }
        return true;
    }
};

你可能感兴趣的:(LeetCode,数独,LeetCode)