【leetcode】Valid Sudoku

Valid Sudoku

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.

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

数独的规则:

在一个9*9的区域内,

每行1-9出现且只出现一次,

每列1-9出现且只出现一次,

在9个子3*3的区域内1-9出现且只出现一次。

 这题允许填空('.'),所以不必要每个数字都出现。

 1 class Solution {
 2 public:
 3     bool isValidSudoku(vector<vector<char> > &board) {
 4         
 5         return  isValidRow(board)&&isValidColumn(board)&&isValidBox(board);
 6     }
 7     
 8     
 9     bool isValidRow(vector<vector<char> > &board)
10     {
11         map<int,bool> hash;
12         for(int i=0;i<9;i++)
13         {
14             for(int j=0;j<9;j++)
15             {
16                 if(board[i][j]=='.') continue;
17                 if(hash.find(board[i][j])!=hash.end()) return false;
18                 hash[board[i][j]]=true;
19                 
20             }
21             hash.clear();
22         }
23         return true;
24     }
25     
26     bool isValidColumn(vector<vector<char> > &board)
27     {
28         map<int,bool> hash;
29         for(int i=0;i<9;i++)
30         {
31             for(int j=0;j<9;j++)
32             {
33                 if(board[j][i]=='.') continue;
34                 if(hash.find(board[j][i])!=hash.end()) return false;
35                 hash[board[j][i]]=true;
36                 
37             }
38             hash.clear();
39         }
40         return true;
41     }
42     
43     bool isValidBox(vector<vector<char> > &board)
44     {
45         int p[9][2]={{0,0},{0,3},{0,6},{3,0},{3,3},{3,6},{6,0},{6,3},{6,6}};
46         map<int,bool> hash;
47         for(int h=0;h<9;h++)
48         {
49             for(int i=0+p[h][0];i<3+p[h][0];i++)
50             {
51                 for(int j=0+p[h][1];j<3+p[h][1];j++)
52                 {
53                     if(board[i][j]=='.') continue;
54                     if(hash.find(board[i][j])!=hash.end()) return false;
55                     hash[board[i][j]]=true;
56                 }
57             }
58             hash.clear();
59         }
60         return true;
61     }
62 };
原文地址:https://www.cnblogs.com/reachteam/p/4183467.html