Problem
Determine whether a Sudoku is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character '.
'.
Example
The following partially filed sudoku is valid.
Note
写两个for循环遍历矩阵中所有的字符,若不是'.
'且不满足数独规则isvalid()
,则返回false
。
对于给定坐标的字符,写一个数独规则的函数isvalid()
判读在某些范围内是否有重复值出现,先比较行,再比较列,最后比较每个小九方格。
Solution
class Solution {
public boolean isValidSudoku(char[][] board) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] != '.' && !isvalid(board, i, j)) return false;
}
}
return true;
}
public boolean isvalid(char[][] board, int row, int col) {
for (int i = 0; i < board.length; i++) {
if (board[row][col] == board[i][col] && row != i) return false;
}
for (int i = 0; i < board[0].length; i++) {
if (board[row][col] == board[row][i] && col != i) return false;
}
for (int i = row/3*3; i < row/3*3+3; i++) {
for (int j = col/3*3; j < col/3*3+3; j++) {
if (board[i][j] == board[row][col] && !(i == row && j == col)) return false;
}
}
return true;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。