m**********n 发帖数: 97 | 1 Valid Sudoku,不是Sudoku solver,只需要检测三条rules就可以了,这是我的代码
public class Solution {
public boolean isValidSudoku(char[][] board) {
int m = board.length;
int n = board[0].length;
if(m != 9 || n != 9) return false;
char[] cube = new char[9];
// check row rule
for(int i = 0; i < m; i++)
{
cube = board[i];
if(!check(cube)) return false;
}
//check column rule
for(int j = 0; j < n; j++)
{
for(int i = 0; i < m; i++)
{
cube[i] = board[i][j];
}
if(!check(cube)) return false;
}
//check each subbox
for(int k = 0; k < 3; k++)
{
for(int h = 0; h < 3; h++)
{
for(int i = 0; i < 9; i++)
{
int row = i/3;
int col = i%3;
cube[i] = board[k*3 + row][h*3 + col];
}
if(!check(cube)) return false;
}
}
return true;
}
public boolean check(char[] cube)
{
int[] visited = new int[9];
for(int i = 0; i < 9; i++)
{
if(cube[i] != '.')
{
int digit = Character.getNumericValue(cube[i]);
if(digit == -1) return false;
if(visited[digit-1] == 1) return false;
visited[digit-1] = 1;
}
}
return true;
}
}
Input: [".87654321","2........","3........","4........","5........","6...
.....","7........","8........","9........"]
Output: false
Expected: true
我在eclipse上跑了一下,发现在是在检查each subbox出的错,感觉像是得到的cube不
正确,可是我看了代码好几遍,都觉得是正确的啊。。。。求大牛给个指导意见~~~谢谢 |
|