您的位置:首页 > 其它

LeetCode Valid Sudoku

2016-02-14 16:58 302 查看
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.

题意:给出一个数独块,已经填了数据,问根据已填的数据判断数独是不是合法的。

思路:在扫描时,如果当前单元格已经填了数, 就判断当前行、当前列、所在的小矩形块的已填的数是不是有重复。如果有重复,说明是不合法的。

代码如下:

class Solution
{
public boolean isValidSudoku(char[][] board)
{
int n = board.length;
Set<Integer> hs = new HashSet<Integer>();

int m = (int)Math.floor(Math.sqrt(n));
for (int i = 1; i <= n; i++)
{
hs.add(i);
}

for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (board[i][j] != '.')
{
Set<Integer> tmp = new HashSet<Integer>(hs);

for (int k = 0; k < n; k++)
{
if (board[i][k] == '.') continue;

int num = board[i][k] - '0';
if (!tmp.contains(num)) return false;
tmp.remove(num);
}

tmp = new HashSet<Integer>(hs);
for (int k = 0; k < n; k++)
{
if (board[k][j] == '.') continue;
int num = board[k][j] - '0';
if (!tmp.contains(num)) return false;
tmp.remove(num);
}

tmp = new HashSet<Integer>(hs);
int row = i / m, col = j / m;
for (int a = row * m; a < (row + 1) * m; a++)
{
for (int b = col * m; b < (col + 1) * m; b++)
{
if (board[a][b] == '.') continue;
int num = board[a][b] - '0';
if (!tmp.contains(num)) return false;
tmp.remove(num);
}
}

}
}
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: