-
Notifications
You must be signed in to change notification settings - Fork 0
/
有效的数独
47 lines (44 loc) · 1.54 KB
/
有效的数独
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
Python
class Solution:
def isValidSudoku(self, board):
Cell = [[] for i in range(9)]
Col = [[] for i in range(9)]
Row = [[] for i in range(9)]
for i, row in enumerate(board):
for j, num in enumerate(row):
if num != '.':
k = (i//3)*3 + j//3 # //为整数除法,/为浮点除法
if num in Row[i] + Col[j] + Cell[k]: # 将3个list顺序拼接
return False
Row[i].append(num)
Col[j].append(num)
Cell[k].append(num)
return True
C++
class Solution
{
public:
bool isValidSudoku(vector<vector<char>>& board)
{
if (board.empty() || board[0].empty()) return false;
int m = board.size(), n = board[0].size();
vector<vector<bool>> rowFlag(m, vector<bool>(n, false));
vector<vector<bool>> colFlag(m, vector<bool>(n, false));
vector<vector<bool>> cellFlag(m, vector<bool>(n, false));
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (board[i][j] >= '1' && board[i][j] <= '9')
{
int c = board[i][j] - '1';
if (rowFlag[i][c] || colFlag[c][j] || cellFlag[3 * (i / 3) + j / 3][c]) return false;
rowFlag[i][c] = true;
colFlag[c][j] = true;
cellFlag[3 * (i / 3) + j / 3][c] = true;
}
}
}
return true;
}
};