Leetcode - Sudoku Solver

[分析] 做Valid Sudoku时表示3*3区块的下标想得很纠结,其实动手把81个格子的坐标都写出来,左上角为(0,0),这个过程中就能发现坐标规律,越勤奋会越聪明~ 这道题目虽然被判为Hard,但看到答案后其实并不难,回溯的题目是有模式可循的,虽然我现在还不是很熟练,但多加练习一定能掌握。早上看到一大神的话,能5天刷一遍leetcode时再问咋还不熟呢,与大家共勉~ 另看参考Code_Ganker的解法:[url]http://blog.csdn.net/linhuanmars/article/details/20748761[/url]


public class Solution {
boolean[][] rows = new boolean[9][9];
boolean[][] cols = new boolean[9][9];
boolean[][] blocks = new boolean[9][9];
public void solveSudoku(char[][] board) {
clean();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.') {
int digitIdx = board[i][j] - '1';
rows[i][digitIdx] = true;
cols[j][digitIdx] = true;
blocks[i / 3 * 3 + j / 3][digitIdx] = true;
}
}
}
solve(board, 0);
}
private boolean solve(char[][] board, int idx) {
while (idx < 81 && board[idx / 9][idx % 9] != '.')
idx++;
if (idx == 81)
return true;
int row = idx / 9, col = idx % 9, blockId = row / 3 * 3 + col / 3;
for (int i = 0; i < 9; i++) {
if (rows[row][i] || cols[col][i] || blocks[blockId][i])
continue;
board[row][col] = (char)('1' + i);
rows[row][i] = cols[col][i] = blocks[blockId][i] = true;
if (solve(board, idx + 1))
return true;
board[row][col] = '.';
rows[row][i] = cols[col][i] = blocks[blockId][i] = false;
}
return false;
}
private void clean() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
rows[i][j] = false;
cols[i][j] = false;
blocks[i][j] = false;
}
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值