Sudoku Solver leetcode java

愛做飯的小瑩子發表於2014-08-01

題目

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

相關文章