您的位置:首页 > 其它

LeetCode: solveSudoku 解题报告

2014-11-01 20:54 225 查看
[b]Sudoku Solver[/b]
Write a program to solve a Sudoku puzzle by filling the empty cells.

Empty cells are indicated by the character '.'.

You may assume that there will be only one unique solution.

public class Solution {
public void solveSudoku(char[][] board) {
// 3:01
if (board == null || board.length == 0 || board[0].length == 0) {
return;
}

dfs(board, 0, 0);
}

public boolean dfs(char[][] board, int x, int y) {
// 3:01
// next row.
if (y >= 9) {
return dfs(board, x + 1, 0);
}

if (x >= 9) {
return true;
}

// skip the number.
if (board[x][y] != '.') {
return dfs(board, x, y + 1);
}

// solve the current node.
// BUG2: c start from 1 not 0.
for (char c = '1'; c <= '9'; c++) {
board[x][y] = c;
if (isValid(board, x, y, c) && dfs(board, x, y + 1)) {
return true;
}
board[x][y] = '.';
}

return false;
}

public boolean isValid(char[][] board, int x, int y, char c) {
// the current row.
for (int i = 0; i < 9; i++) {
if (y != i && c == board[x][i]) {
return false;
}
}

// the current col.
for (int i = 0; i < 9; i++) {
// BUG1: should use board[i][y]
if (x != i && c == board[i][y]) {
return false;
}
}

// the current block.
int startX = x / 3 * 3;
int startY = y / 3 * 3;
for (int k = 0; k < 9; k++) {
int indexX = startX + k / 3;
int indexY = startY + k % 3;
if (indexX == x && indexY == y) {
continue;
}

if (board[indexX][indexY] == c) {
return false;
}
}

return true;
}
}


View Code

[b]GITHUB代码:[/b]

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/hash/SolveSudoku.java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: