[LeetCode] #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.

本题是检验一张9X9的矩阵是否满足数独的特性。即里面存有数字或者‘.’,判断已有的数字是否符合九宫格的规则。思路是开辟三个9*9的bool,分别代表行row,列col,和子九宫subSudo,判断是否有非法数字,如果有就判断输出非法,否则一直进行到最后。都没有非法元素,那就输出true。时间:12ms。代码如下:

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        if (board.size() != 9)
            return false;
        bool row[9][9], col[9][9], subSudo[9][9];
        memset(row, false, sizeof row);
        memset(col, false, sizeof col);
        memset(subSudo, false, sizeof subSudo);
        for (size_t i = 0; i < 9; ++i){
            if (board[i].size() != 9)
                return false;
            for (size_t j = 0; j < 9; ++j){
                if (board[i][j] == '.')
                    continue;
                int c = board[i][j] - '1';
                if (row[i][c] || col[j][c] || subSudo[3 * (i / 3) + j / 3][c])
                    return false;
                row[i][c] = col[j][c] = subSudo[3 * (i / 3) + j / 3][c] = true;
            }
        }
        return true;
    }
};
“If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
原文地址:https://www.cnblogs.com/Scorpio989/p/4580078.html