*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。

静心尽力!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值