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

LeetCode 37 Sudoku Solver(求解数独)

时间:2017-03-11 15:44:03      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:.com   private   code   tab   font   board   system   判断   循环   

 
Problem : 解决数独问题,给出一个二维数组,将这个数独进行求解。
 
思路:
  1. 嵌套循环,三层循环体,每一行,每一列,填入从1到9的数字。判断填入之后是否合理
  2. 判断数独是否合理的函数
 
参考代码: 
 
package leetcode_50;

/***
 * 
 * @author pengfei_zheng
 * 求解数独问题
 */
public class Solution37 {
    public static void solveSudoku(char[][] board) {
        if(board==null ||board.length ==0)
                return;
        else
                solve(board);
    }

    private static boolean solve(char[][] board) {
        for(int i = 0 ; i < 9;i++){
            for(int j = 0 ; j < 9;j++){
                if(board[i][j]==‘.‘){
                    for(char c = ‘1‘; c<=‘9‘;c++){
                        if(isValid(board,i,j,c)){
                            board[i][j]=c;
                            if(solve(board))
                                return true;
                            else
                                board[i][j]=‘.‘;
                        }
                    }
                    return false;
                }
            }
        }
        return true;
    }

    private static boolean isValid(char[][] board, int row, int column, char c) {
        for(int i = 0 ; i < 9; i ++){
            if(board[row][i]==c) return false;
            if(board[i][column]==c) return false;
            if(board[3 * (row / 3) + i / 3][ 3 * (column / 3) + i % 3] != ‘.‘ && 
                    board[3 * (row / 3) + i / 3][3 * (column / 3) + i % 3] == c) return false; //check 3*3 block
        }
        return true;
    }
    public static void main(String[]args){
        long start = System.currentTimeMillis();
        char[][] board={{‘8‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘},
                        {‘.‘,‘.‘,‘3‘,‘6‘,‘.‘,‘.‘,‘.‘,‘.‘,‘.‘},
                        {‘.‘,‘7‘,‘.‘,‘.‘,‘9‘,‘.‘,‘2‘,‘.‘,‘.‘},
                        {‘.‘,‘5‘,‘.‘,‘.‘,‘.‘,‘7‘,‘.‘,‘.‘,‘.‘},
                        {‘.‘,‘.‘,‘.‘,‘.‘,‘4‘,‘.‘,‘7‘,‘.‘,‘.‘},
                        {‘.‘,‘.‘,‘.‘,‘1‘,‘.‘,‘5‘,‘.‘,‘3‘,‘.‘},
                        {‘.‘,‘.‘,‘1‘,‘.‘,‘.‘,‘.‘,‘.‘,‘6‘,‘8‘},
                        {‘.‘,‘.‘,‘8‘,‘5‘,‘.‘,‘.‘,‘.‘,‘1‘,‘.‘},
                        {‘.‘,‘9‘,‘.‘,‘.‘,‘.‘,‘.‘,‘4‘,‘.‘,‘.‘}
                    };
        solveSudoku(board);
        long end = System.currentTimeMillis();
        for(int i = 0 ; i < 9 ; i ++){
            for(int j = 0 ; j < 9 ;j ++){
                System.out.print(board[i][j]+" ");
            }
            System.out.println();
        }
        System.out.println("耗时: "+ (double)(end-start)/1000+" s");
    }
}

 

LeetCode 37 Sudoku Solver(求解数独)

标签:.com   private   code   tab   font   board   system   判断   循环   

原文地址:http://www.cnblogs.com/zpfbuaa/p/6534906.html

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