Sudoku Solver leetcode java

题目

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.

 

题解:

第一反应就是N皇后问题。就是一点点尝试着填数,不行的话就回溯,直到都填满就返回。

如果对一个格子尝试从0~9都不行,那么说明整个sudoku无解,返回false就好。

对整个棋盘所有'.'都填完了,那么就可以返回true了。

 1     public void solveSudoku(char[][] board) {
 2         if (board==null||board.length==0)
 3             return;
 4         helper(board);
 5     }
 6     
 7     private boolean helper(char[][] board){
 8         for(int i=0; i<board.length; i++){
 9             for (int j=0; j<board[0].length; j++){
10                 if (board[i][j]=='.'){
11                     for (char num='1'; num<='9'; num++){//尝试
12                         if(isValid(board, i, j, num)){
13                             board[i][j]=num;
14                             
15                             if (helper(board))
16                                 return true;
17                             else
18                                 board[i][j]='.';//回退
19                         }
20                     }
21                     return false;
22                 }
23             }
24         }
25         
26         return true;
27     }
28     
29     private boolean isValid(char[][] board, int i, int j, char c){
30         // check column
31         for (int row=0; row<9; row++)
32             if (board[row][j] == c)
33                 return false;
34         
35        // check row
36         for (int col=0; col<9; col++)
37             if (board[i][col]==c)
38                 return false;
39       
40         // check block
41         for(int row=i/3*3; row<i/3*3+3; row++)
42             for (int col=j/3*3; col<j/3*3+3; col++)
43                 if (board[row][col]==c)
44                     return false;
45                     
46         return true;
47     }

Reference:http://rleetcode.blogspot.com/2014/01/sudoku-solver-java.html

posted @ 2014-08-01 09:55  爱做饭的小莹子  阅读(4142)  评论(0编辑  收藏  举报