*36. Valid Sudoku

題目描述:

Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.


A partially filled sudoku which is valid.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

Example 1:

Input:
[
  ["5","3",".",".","7",".",".",".","."],
  ["6",".",".","1","9","5",".",".","."],
  [".","9","8",".",".",".",".","6","."],
  ["8",".",".",".","6",".",".",".","3"],
  ["4",".",".","8",".","3",".",".","1"],
  ["7",".",".",".","2",".",".",".","6"],
  [".","6",".",".",".",".","2","8","."],
  [".",".",".","4","1","9",".",".","5"],
  [".",".",".",".","8",".",".","7","9"]
]
Output: true

 代碼:

class Solution {
public:
    void initial(bool match[10][10]){
        for(int i = 1; i <= 9; i++){
            for(int j = 1; j <= 9; j++){
                match[i][j] = false;
            }
        }
    }
    bool isValidSudoku(vector<vector<char>>& board) {
        bool row[10][10];
        bool column[10][10];
        bool box[10][10];
        initial(row);
        initial(column);
        initial(box);
        bool flag = false;    
        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 + 1][num]){
                    flag = true;
                    break;
                }else row[i + 1][num] = true;
                
                if(column[j + 1][num]){
                    flag = true;
                    break;
                }else column[j + 1][num] = true;
                
                int boxIndex = (i / 3) * 3 + j / 3 + 1;
                if(box[boxIndex][num]){
                    flag = true;
                    break;
                }else box[boxIndex][num] = true;
            }
            if(flag) break;
        }
        return !flag;
    }
};

題目要求判斷當前數獨是否是正確的,一次AC,之所以給星標記是因爲本題中二維數組作爲形參的傳入方式自己開始不正確。解題方法很簡單,也很容易理解,如下:

首先初始化三個布爾類型的二維數組,row[10][10],column[10][10],box[10][10]。row[n][num]代表在數獨盤中,第n行是否有num這個數,若有則爲true,反之爲false。column[n][num]代表在數獨盤中,第n列是否有num這個數,若有則爲true,反之爲false。box數組也同理。然後只要遍歷一下數獨盤即可,當讀取到數獨盤中的一個數時,判斷它是屬於第幾行,第幾列,第幾個box。並依次查看對應數組中的值是否爲true,即是否存在這個值。若已經存在,則return false。

靜心盡力!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章