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.

分析

數(shù)獨(dú)規(guī)則是每行每列以及沒個小方框中的數(shù)字都是0~9且都沒有重復(fù)的數(shù)字。
所以就分別遍歷每行、每列以及沒個小方框,判斷有無重復(fù)的數(shù)字即可。

實(shí)現(xiàn)

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        for(int i=0; i<9; i++){
            int trow[9]={0}, tcol[9]={0}, tblk[9]={0};
            for(int j=0; j<9; j++){
                if(board[i][j]!='.'){
                    int nrow = board[i][j] - '0' - 1;
                    if(trow[nrow]) return false;
                    trow[nrow]++;
                }
                if(board[j][i]!='.'){
                    int ncol = board[j][i] - '0' - 1;
                    if(tcol[ncol]) return false;
                    tcol[ncol]++;
                }
                int x = i / 3 * 3 + j / 3;
                int y = i % 3 * 3 + j % 3;
                if(board[x][y]!='.'){
                    int nblk = board[x][y] - '0' - 1;
                    if(tblk[nblk]) return false;
                    tblk[nblk]++;
                }
            }
        }
        return true;
    }
};

思考

在這里沒有判斷出現(xiàn)除'1'~'9'和'.'之外的符號怎么辦,嚴(yán)謹(jǐn)點(diǎn)應(yīng)該加上。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容