其他分享
首页 > 其他分享> > 有效的数独 -- LeetCode -- 9.14

有效的数独 -- LeetCode -- 9.14

作者:互联网

有效的数独

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

  1. 数字 1-9 在每一行只能出现一次。
  2. 数字 1-9 在每一列只能出现一次。
  3. 数字 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

遍历就行了:

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        int book[10];
        memset(book,0,sizeof(book));
        for(int i = 0; i < 9; i++){
            for(int j = 0; j < 9; j++){
                if(board[i][j] >= '0' && board[i][j] <= '9'){//横着的
                    int a = board[i][j] - '0';
                    if(book[a] == 1)return false;
                    else            book[a] = 1;
                }
            }
            memset(book,0,sizeof(book));
            for(int j = 0; j < 9; j++){
                if(board[j][i] >= '0' && board[j][i] <= '9'){//竖着的
                    int a = board[j][i] - '0';
                    if(book[a] == 1)return false;
                    else            book[a] = 1;
                }
            }
            memset(book,0,sizeof(book));
        }
        for(int i = 0; i < 9; i += 3){
            for(int j = 0; j < 9; j += 3){
                memset(book,0,sizeof(book));
                for(int k = 0; k < 3; k++){//每个 3 * 3的矩形
                    for(int l = 0; l < 3; l++){
                        if(board[i + k][j + l] >= '0' && board[i + k][j + l] <= '9'){
                        int a = board[i + k][j + l] - '0';
                        if(book[a] == 1)return false;
                        else            book[a] = 1;
                        }
                    }
                }
            }
        }
    return true;
    }
    
};

  

标签:数字,--,9.14,int,book,board,&&,LeetCode,数独
来源: https://www.cnblogs.com/rongrongrong/p/15306371.html