leetcode114:valid-sudoku

题目描述

根据数独的规则Sudoku Puzzles - The Rules.判断给出的局面是不是一个符合规则的数独局面
数独盘面可以被部分填写,空的位置用字符'.'.表示
这是一个部分填写的符合规则的数独局面

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.


class Solution {
public:
    bool isValidSudoku(vector<vector<char> > &board) {
        //记录已经出现的数,如3出现,则row[3]=1
        int row[10] = {0};//之所以是10,因为下标最大是9
        int col[9][10] = {0};
        int square[9][10] = {0};
         
        //行遍历,两层循环即可,只要找到重复的数即返回false
        for(int i=0; i<9; i++){
            //由于行重复使用了,所以每次都要清空
            memset(row, 0, sizeof(row));
            for(int j=0; j<9; j++){
                if(board[i][j] != '.'){
                    if(!check(row, board[i][j] - '0') ||
                       !check(col[j], board[i][j] - '0') ||
                       //九宫格的序号:i/3*3 + j/3
                       !check(square[i/3*3 + j/3], board[i][j] - '0')                
                      )
                        return false;
                }
            }
        }
         
        return true;       
    }
     
    bool check(int a[], int v){
        //如果每行或每列或每个九宫格出现了重复的数,那么返回false
        if(a[v] == 1) return false;
        a[v] = 1;
        return true;
    }
};

posted on 2020-08-01 15:54  滚雪球效应  阅读(91)  评论(0编辑  收藏  举报