Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits
1-9
without repetition. - Each column must contain the digits
1-9
without repetition. - Each of the 9
3x3
sub-boxes of the grid must contain the digits1-9
without repetition.
A partially filled sudoku which is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
判断一个数组是否合法,每一行,每一列以及每一个方格只包含一个1--9数字,不能有重复。
检查每一行 检查每一列 检查每一个方格
class Solution:
def isValidSudoku(self, board):
#检查行
for i in range(0, 9):
row = [v for v in board[i] if v !='.']
#print('row',row)
if len(row)!=len(set(row)):
return False
#检查列
for c in range(0, 9):
col=[]
for r in range(0, 9):
if board[r][c]!='.':
col.append(board[r][c])
#print('row',col)
if len(col)!=len(set(col)):
return False
#检查子矩阵
for r in range(1, 4):
for c in range(1, 4):
arr = []
rs = 3*(r-1)
re = (3*r-1)
cs = 3*(c-1)
ce = (3*c-1)
for i in range(rs, re+1):
for j in range(cs, ce+1):
if board[i][j]!='.':
arr.append(board[i][j])
#print('arr',arr)
if len(arr)!=len(set(arr)):
return False
return True
看一下大神的解法:
row表示每一行各个数字是否出现 row[3][4]表示第四行数字四出现过
col表示每一列各个数字是否出现
box表示每一个方格,数字是否出现
public static boolean isValidSudoku(char[][] board) {
boolean[][] row = new boolean[9][9];
boolean[][] col = new boolean[9][9];
boolean[][] box = new boolean[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c = board[i][j];
if (c == '.')
continue;
if (c < '0' || c > '9')
return false;
int number = c - '1';
if (row[i][number] || col[j][number] || box[(i / 3) * 3 + j / 3][number])
return false;
row[i][number] = true;
col[j][number] = true;
box[(i / 3) * 3 + j / 3][number] = true;
}
}
return true;
}