[leetcode]Sudoku Solver

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.

A sudoku puzzle...

 

...and its solution numbers marked in red.

算法思路:

典型的DFS,与N-Queens其实没太大区别,只是冲突不同,而冲突的判断方式,在[leetcode]Valid Sudoku中已经讲得很清楚了。

代码如下:

 1 public class Solution {
 2     boolean over = false;
 3     public void solveSudoku(char[][] board) {
 4         if(board == null || board.length != 9 || board[0].length != 9) return;
 5         boolean[][] row = new boolean[9][9];
 6         boolean[][] col = new boolean[9][9];
 7         boolean[][] matrix = new boolean[9][9];
 8         for(int i = 0; i < 9; i++){//初始化冲突表
 9             for(int j = 0; j < 9; j++){
10                 if(board[i][j] != '.'){
11                     int n = board[i][j] - '1';
12                     row[i][n] = col[j][n] = matrix[i - i % 3 + j / 3][n] = true;
13                 }
14             }
15         }
16         dfs(board,0,0,row,col,matrix);
17     }
18     private void dfs(char[][] board,int i ,int j,boolean[][] row,boolean[][] col,boolean[][] matrix){
19         if(i > 8){
20             over = true;
21             return;
22         }
23         if(board[i][j] != '.'){
24             if(j < 8){
25                 dfs(board, i, j + 1, row, col, matrix);
26             }else{
27                 dfs(board, i + 1, 0, row, col, matrix);
28             }
29         }else{
30             for(int k = 0; k < 9; k++){
31                 if(row[i][k] || col[j][k] || matrix[i - i % 3 + j / 3][k]) continue;
32                 row[i][k] = col[j][k] = matrix[i - i % 3 + j / 3][k] = true;
33                 board[i][j] = (char)('1' + k);
34                 if(j < 8){
35                     dfs(board, i, j + 1, row, col, matrix);
36                 }else{
37                     dfs(board, i + 1, 0, row, col, matrix);
38                 }
39                 if(over) return;
40                 row[i][k] = col[j][k] = matrix[i - i % 3 + j / 3][k] = false;
41                 board[i][j] = '.';
42             }
43         }
44     }
45 }

 

posted on 2014-08-09 21:17  喵星人与汪星人  阅读(212)  评论(0编辑  收藏  举报