问题:
请判定一个数独是否有效。
该数独可能只填充了部分数字,其中缺少的数字用 .
表示。
样例:
样例1:
输入:
["53..7....","6..195...",".98....6.","8...6...3","4..8.3..1","7...2...6",".6....28.","...419..5","....8..79"]
输出: true
样例说明:
这个数独如下图所示,他是合法的。
样例 2:
输入:
["53..75...","6..195...",".98....6.","8...6...3","4..8.3..1","7...2...6",".6....28.","...419..5","....8..79"]
输出: false
样例说明:
这个数独如下图所示。他是不合法的因为他的第一行和第六列有两个5。
说明
What is Sudoku
?
- http://sudoku.com.au/TheRules.aspx
- https://zh.wikipedia.org/wiki/數獨
- https://en.wikipedia.org/wiki/Sudoku
- http://baike.baidu.com/subview/961/10842669.htm
注意事项
一个合法的数独(仅部分填充)并不一定是可解的。我们仅需使填充的空格有效即可。
python:
class Solution:
"""
@param board: the board
@return: whether the Sudoku is valid
"""
def isValidSudoku(self, board):
# write your code here
if len(board) != 9 or len(board[0]) != 9:
return False
for i in range(9):
for j in range(9):
if board[i][j] != '.':
for k in range(j+1, 9):
if board[i][k] == board[i][j]:
return False
for m in range(i+1, 9):
if board[m][j] == board[i][j]:
return False
squareI = i // 3
squareJ = j // 3
for p in range(i, squareI*3+3):
if p == i:
continue
for q in range(j, squareJ*3+3):
if q == j:
continue
if board[p][q] == board[i][j]:
return False
return True
C++:
class Solution {
public:
/**
* @param board: the board
* @return: whether the Sudoku is valid
*/
bool isValidSudoku(vector<vector<char>> &board) {
// write your code here
if(board.size() != 9 || board[0].size() != 9)
{
return false;
}
for(int i = 0; i < 9; i++)
{
for(int j = 0; j < 9; j++)
{
if(board[i][j] == '.')
{
continue;
}
for(int k = j+1; k < 9; k++)
{
if(board[i][k] == board[i][j])
{
return false;
}
}
for(int m = i+1; m < 9; m++)
{
if(board[m][j] == board[i][j])
{
return false;
}
}
int squareI = i / 3;
int squareJ = j / 3;
for(int p = i; p < squareI*3+3; p++)
{
if(p == i)
{
continue;
}
for(int q = j; q < squareJ*3+3; q++)
{
if(q == j)
{
continue;
}
if(board[p][q] == board[i][j])
{
return false;
}
}
}
}
}
return true;
}
};