[LeetCode] 36. Valid Sudoku

来源:互联网 发布:过目不忘的句子 知乎 编辑:程序博客网 时间:2024/06/05 14:58

思路:
借鉴了https://discuss.leetcode.com/topic/9748/shared-my-concise-java-code的思路, 准备三个数组, 分别记录当前行, 当前列, 当前子宫格的数字出现情况, 个人感觉唯一的难点就在子宫格下标的计算, 要找找规律.

bool isValidSudoku(vector<vector<char>>& board) {    bool row[9], col[9], sub[9];    for (int i = 0; i < 9; i++) {        memset(row, false, sizeof(bool) * 9);        memset(col, false, sizeof(bool) * 9);        memset(sub, false, sizeof(bool) * 9);        for (int j = 0; j < 9; j++) {            if (board[i][j] != '.') {                if (row[board[i][j] - '0' - 1])                    return false;                else row[board[i][j] - '0' - 1] = true;             }            if (board[j][i] != '.') {                if (col[board[j][i] - '0' - 1])                    return false;                else col[board[j][i] - '0' - 1] = true;             }            int rowInd = 3 * (i / 3) + j / 3;            int colInd = 3 * (i % 3) + j % 3;            if (board[rowInd][colInd] != '.') {                if (sub[board[rowInd][colInd] - '0' - 1])                    return false;                else sub[board[rowInd][colInd] - '0' - 1] = true;             }        }    }    return true;}
0 0