[LeetCode] Valid Sudoku 驗證數獨

Grandyang發表於2015-04-13

 

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.

 

這道題讓我們驗證一個方陣是否為數獨矩陣,判斷標準是看各行各列是否有重複數字,以及每個小的3x3的小方陣裡面是否有重複數字,如果都無重複,則當前矩陣是數獨矩陣,但不代表待數獨矩陣有解,只是單純的判斷當前未填完的矩陣是否是數獨矩陣。那麼根據數獨矩陣的定義,我們在遍歷每個數字的時候,就看看包含當前位置的行和列以及3x3小方陣中是否已經出現該數字,那麼我們需要三個標誌矩陣,分別記錄各行,各列,各小方陣是否出現某個數字,其中行和列標誌下標很好對應,就是小方陣的下標需要稍稍轉換一下,具體程式碼如下:

 

class Solution {
public:
    bool isValidSudoku(vector<vector<char> > &board) {
        if (board.empty() || board[0].empty()) return false;
        int m = board.size(), n = board[0].size();
        vector<vector<bool> > rowFlag(m, vector<bool>(n, false));
        vector<vector<bool> > colFlag(m, vector<bool>(n, false));
        vector<vector<bool> > cellFlag(m, vector<bool>(n, false));
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (board[i][j] >= '1' && board[i][j] <= '9') {
                    int c = board[i][j] - '1';
                    if (rowFlag[i][c] || colFlag[c][j] || cellFlag[3 * (i / 3) + j / 3][c]) return false;
                    rowFlag[i][c] = true;
                    colFlag[c][j] = true;
                    cellFlag[3 * (i / 3) + j / 3][c] = true;
                }
            }
        }
        return true;
    }
};

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章