码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Sudoku Solver

时间:2014-12-02 15:05:17      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   sp   for   on   

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.

 

Solution:

http://blog.csdn.net/zxzxy1988/article/details/8586289

 1 public class Solution {
 2     public void solveSudoku(char[][] board) {
 3         mySudokuSolver(board);
 4     }
 5 
 6     private boolean mySudokuSolver(char[][] board) {
 7         // TODO Auto-generated method stub
 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(int k=1;k<=9;++k){
12                         board[i][j]=(char) (k+‘0‘);
13                         if(isValid(board,i,j)&&mySudokuSolver(board)){
14                             return true;
15                         }
16                         board[i][j]=‘.‘;  //这里这个细节不要忘掉!!,你把后边儿的“.“改成数字后,发现做不下去了,得回溯,那你
                           //得把这个数字改回"."啊
17 } 18 return false; 19 } 20 } 21 } 22 return true; 23 } 24 25 private boolean isValid(char[][] board, int row, int col) { 26 // TODO Auto-generated method stub 27 for(int i=0;i<board.length;++i){ 28 if(i!=row&&board[i][col]==board[row][col]) 29 return false; 30 } 31 for(int i=0;i<board[0].length;++i){ 32 if(i!=col&&board[row][i]==board[row][col]) 33 return false; 34 } 35 for(int i=(row/3)*3;i<(row/3+1)*3;++i){ 36 for(int j=(col/3)*3;j<(col/3+1)*3;++j){ 37 if(i!=row&&j!=col&&board[i][j]==board[row][col]) 38 return false; 39 } 40 } 41 return true; 42 } 43 }

 

[Leetcode] Sudoku Solver

标签:style   blog   http   io   ar   color   sp   for   on   

原文地址:http://www.cnblogs.com/Phoebe815/p/4137277.html

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