活跃农民
- 积分
- 500
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-4-24
- 最后登录
- 1970-1-1
|
嗯,同上,你的代码可能不全,我觉得isValidSudoku(..)和markFlag应该是两个function。你的isValidSudoku(..)的if..else..那块代码没有。markFlag会被isValidSudoku(..) 这个function叫到。另外,我觉得code 里面int index = c - '0' 应该改成 int index = c - '1',因为flag array 的index 是从0开始的,而sudoku里面的号码是从1开始的。eg 如果c = ‘1’ ,那么刚好对应flag里面0的位置 即flag[c - '1'].下面是我的code,你可以参考下:)
我也是刚开始刷题不久,我是用leetcode online judge https://leetcode.com/problemset/algorithms/ 我觉得这个网站不错 可以提交自己的代码test,里面也有很多test cases。楼主可以试下,看喜不喜欢:p 最后祝刷题顺利:)
public class Solution {
public boolean isValidSudoku(char[][] board) {
boolean[] used = new boolean[9];
int i;
int j;
//check rows
for (i = 0; i < 9; i++) {
Arrays.fill(used, false);
for (j = 0; j < 9; j++) {
if (!isValid(board[i][j], used)) {
return false;
}
}
}
//check columns
for (j = 0; j < 9; j++) {
Arrays.fill(used, false);
for (i = 0; i < 9; i++) {
if (!isValid(board[i][j], used)) {
return false;
}
}
}
//check grids
int m;
int n;
for (m = 0; m < 3; m++) {
for (n = 0; n < 3; n++) {
Arrays.fill(used, false);
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
if (!isValid(board[3 * m + i][ 3 * n + j],used))
return false;
}
}
}
}
return true;
}
public boolean isValid(char ch, boolean[] used) {
if (ch == '.')
return true;
if (used[ch - '1']) {
return false;
}
else {
used[ch - '1'] = true;
return true;
}
}
} |
|