Leetcode 36. 有效的数独 中等 数组遍历 精选 TOP 面试题

36. 有效的数独

题目:

请你判断一个 9 x 9 的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。

数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)
 

注意:

一个有效的数独(部分已被填充)不一定是可解的。
只需要根据以上规则,验证已经填入的数字是否有效即可。
空白格用 '.' 表示。
 

示例 1:


输入:board =
[["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"]]
输出:true

 

思路:

用二维矩阵,记录横行或竖行中,1-9出现的次数。有重复出现就报错

方框同理

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        int m=board.size();
        int n=board[0].size();
        // 横行记录
        vector<vector<int>> n1(m,vector<int>(10));
        // 竖行记录
        vector<vector<int>> n2(n,vector<int>(10));
        for(int i=0;i<m;++i){
            for(int j=0;j<n;++j){
                char c=board[i][j];
                if(c=='.') continue;
                int a=c-'0';
                if(n1[i][a]!=0||n2[j][a]!=0){
                    return false;
                }
                n1[i][a]=1;
                n2[j][a]=1;
            }
        }
        // 方框记录
        vector<vector<int>> n3(m,vector<int>(10));
        int count=0;
        for(int i=0;i<m;i+=3){
            for(int j=0;j<n;j+=3){
                // 遍历方框中的坐标
                for(int ii=i;ii<i+3;++ii){
                    for(int jj=j;jj<j+3;++jj){
                        char c=board[ii][jj];
                        if(c=='.') continue;
                        int a=c-'0';
                        if(n3[count][a]!=0)
                            return false;
                        n3[count][a]=1;
                    }
                }
                count++;
            }
        }
        return true;
    }
};

 

posted @ 2022-06-09 16:43  鸭子船长  阅读(29)  评论(0编辑  收藏  举报