leetcode专题训练 36. Valid Sudoku

按照题中的三个条件判断一下就行了。

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        int row[10][11], col[10][11], box[10][11];
        memset(row, 0, sizeof(row));
        memset(col, 0, sizeof(col));
        memset(box, 0, sizeof(box));
        for (int i = 0; i < 9; i++) { //行
            for (int j = 0; j < 9; j++) {
                if (board[i][j] == '.') continue;
                int num = board[i][j] - '0';
                if (row[i][num] != 0) return false;
                if (col[j][num] != 0) return false;
                row[i][num] = 1;
                col[j][num] = 1;
                if (i / 3 == 0) {
                    if (j / 3 == 0) {
                        if (box[0][num] != 0) return false;
                        box[0][num] = 1;
                    } else if (j / 3 == 1) {
                        if (box[3][num] != 0) return false;
                        box[3][num] = 1;
                    } else {
                        if (box[6][num] != 0) return false;
                        box[6][num] = 1;
                    }
                } else if (i / 3 == 1) {
                    if (j / 3 == 0) {
                        if (box[1][num] != 0) return false;
                        box[1][num] = 1;
                    } else if (j / 3 == 1) {
                        if (box[4][num] != 0) return false;
                        box[4][num] = 1;
                    } else {
                        if (box[7][num] != 0) return false;
                        box[7][num] = 1;
                    }
                } else {
                    if (j / 3 == 0) {
                        if (box[2][num] != 0) return false;
                        box[2][num] = 1;
                    } else if (j / 3 == 1) {
                        if (box[5][num] != 0) return false;
                        box[5][num] = 1;
                    } else {
                        if (box[8][num] != 0) return false;
                        box[8][num] = 1;
                    }
                }
            }
        }
        return true;
    }
};
发布了201 篇原创文章 · 获赞 26 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/Ema1997/article/details/96349558