标签:des style blog http io color os ar 使用
Sudoku Solver
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.
SOLUTION:
ref: http://blog.csdn.net/fightforyourdream/article/details/16916985
采用递归+回溯模板来解决此问题:
1. 判定DFS的退出条件。
(1) y越界,应该往下一行继续解。
(2)x越界,代表数独解完,应该返回。
2. DFS的主体部分:
把9个可能的值遍历一次,如果是OK的(使用独立 的Valid函数来判定行,列,BLOCK是否符合),继续DFS,否则回溯。
3. 最后的返回值:
如果所有的可能性遍历都没有找到TRUE,最后应该返回FALSE,也就是当前情况无解。这个时候DFS会自动回溯到上一层再查找别的可能解。
1 public class Solution { 2 public void solveSudoku(char[][] board) { 3 dfs(board, 0, 0); 4 } 5 6 public boolean dfs(char[][] board, int x, int y) { 7 // go to next row. 8 if (y == 9) { 9 y = 0; 10 x++; 11 } 12 13 // done 14 if (x >= 9) { 15 return true; 16 } 17 18 // Skip the solved point. 19 if (board[x][y] != ‘.‘) { 20 return dfs(board, x, y + 1); 21 } 22 23 // Go throught all the possibilities. 24 for (int k = 0; k < 9; k++) { 25 board[x][y] = (char)(‘1‘ + k); 26 // SHOULD RETURN HERE IF INVALID. 27 if (isValid(board, x, y) && dfs(board, x, y + 1)) { 28 return true; 29 } 30 board[x][y] = ‘.‘; 31 } 32 33 // because all the possibility is impossiable. 34 return false; 35 } 36 37 public boolean isValid(char[][] board, int x, int y) { 38 // Judge the column. 39 for (int i = 0; i < 9; i++) { 40 if (i != x && board[i][y] == board[x][y]) { 41 return false; 42 } 43 } 44 45 // Judge the row. 46 for (int i = 0; i < 9; i++) { 47 if (i != y && board[x][i] == board[x][y]) { 48 return false; 49 } 50 } 51 52 // Judge the block. 53 int i = x / 3 * 3; 54 int j = y / 3 * 3; 55 for (int k = 0; k < 9; k++) { 56 int xIndex = i + k / 3; 57 int yIndex = j + k % 3; 58 if (xIndex == x && yIndex == y) { 59 continue; 60 } 61 62 if (board[xIndex][yIndex] == board[x][y]) { 63 return false; 64 } 65 } 66 67 return true; 68 } 69 }
GITHUB代码:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/hash/SolveSudoku.java
标签:des style blog http io color os ar 使用
原文地址:http://www.cnblogs.com/yuzhangcmu/p/4067733.html