您的位置:首页 > 其它

LeetCode - Sudoku Solver

2015-04-01 01:13 316 查看
https://leetcode.com/problems/sudoku-solver/

这道题我发现大部分的解决方法都是加一个isValid函数,来判断当前数字是否合法。

比如:

/article/1378332.html

http://www.ninechapter.com/solutions/sudoku-solver/

但是我想这样的话就得每次遍历当前列,当前行,当前3×3方格。所以还不如设置hashset数组来记录,然后就可以直接通过hashSet判断是否合法了。

而且他们都是每次递归只检查当前格,我想,如果可以一直前进,前进到是'.'的格,再进入下一次递归,就可以减少递归次数了呀。

但是,写出来代码之后一直不对。。。调了半天也没看出哪里不对。。。。。真是。。。。

而且错误情况也很奇葩,前面都对了,最后一行死活不对。。。。。。

Input:["..9748...","7........",".2.1.9...","..7...24.",".64.1.59.",".98...3..","...8.3.2.","........6","...2759.."]
Output:["519748632","783652419","426139875","357986241","264317598","198524367","975863124","832491756","...2759.3"]
Expected:["519748632","783652419","426139875","357986241","264317598","198524367","975863124","832491756","641275983"]
调试之后发现,始终进入不到最后一行前面几个数,但是因为这个程序实在递归太多,到最后也没看出为啥会出现这种情况。。。。

总之也是醉了,头都晕了也没看出来到底是啥问题,还是先放在这里,过段时间再看看吧,另外,到时候也把他们那种解法也写写吧,可能那种解法真的不容易错。。。。

public class Solution {

public void solveSudoku(char[][] board) {
HashSet<Integer>[] rows = new HashSet[9];
for(int i=0; i<9; i++) rows[i] = new HashSet<Integer>();

HashSet<Integer>[] cols = new HashSet[9];
for(int i=0; i<9; i++) cols[i] = new HashSet<Integer>();

HashSet<Integer>[] squares = new HashSet[9];
for(int i=0; i<9; i++) squares[i] = new HashSet<Integer>();

for(int i=0; i<9; i++){
for(int j=0; j<9; j++){
if(Character.isDigit(board[i][j])){
rows[i].add(board[i][j]-'0');
cols[j].add(board[i][j]-'0');
squares[(i/3)*3+(j/3)].add(board[i][j] - '0');
}
}
}

helper(board,rows, cols, squares, 0, 0);

}

public boolean helper(char[][] board, HashSet<Integer>[] rows, HashSet<Integer>[] cols, HashSet<Integer>[] squares, int row, int col){
if(row >= 9) return true;
for(int i=row; i<9; i++){
for(int j=col; j<9; j++){
if(Character.isDigit(board[i][j])){
continue;
}
else{
for(int k=1; k<=9; k++){
if(rows[i].contains(k) || cols[j].contains(k) || squares[(i/3)*3+(j/3)].contains(k)) continue;
else{
rows[i].add(k);
cols[j].add(k);
squares[(i/3)*3+(j/3)].add(k);
board[i][j] = (char)('0'+k);
int nextrow;
int nextcol;
if(j>=8){
nextrow = i+1;
nextcol = 0;
}
else{
nextrow = i;
nextcol = j+1;
}
if(helper(board, rows, cols, squares, nextrow, nextcol)) return true;
rows[i].remove(k);
cols[j].remove(k);
squares[(i/3)*3+(j/3)].remove(k);
board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: