码迷,mamicode.com
首页 > 编程语言 > 详细

Sudoku Solver leetcode java

时间:2014-08-01 10:38:21      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   java   strong   io   for   

题目

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.

bubuko.com,布布扣

A sudoku puzzle...

bubuko.com,布布扣

...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

Sudoku Solver leetcode java,布布扣,bubuko.com

Sudoku Solver leetcode java

标签:style   blog   http   color   java   strong   io   for   

原文地址:http://www.cnblogs.com/springfor/p/3884252.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!