首页 > 其他 > 详细

Sudoku

时间:2015-01-17 11:08:40      阅读:109      评论:0      收藏:0      [点我收藏+]

Inefficient Print All

public static void main(String[] args)
        {
         solveSudoku(new char[N][N]);
             
             
        }
     static int N =9; //4
     static int s = 3;  //2
     static boolean solved = false;
     public static void solveSudoku(char[][] board){
            solveSudoku(board, 0, 0);
        }
        
        private static void solveSudoku(char[][] board, int rowFrom, int colFrom) {
            
            for(int r = rowFrom; r<N; ++r)
            {
                for(int c = colFrom; c<N; ++c)
                {
                    int n = 1;
                    while(board[r][c]==‘\0‘ && n<=N)
                    {
                        if(isValid(board, r, c, Character.forDigit(n, 10)))
                        {
                            board[r][c] = Character.forDigit(n, 10);
                            solveSudoku(board, r, c+1);
                            if(solved)  //comment this out to get all sudoku
                                return;
                            board[r][c] = ‘\0‘;
                        }
                        ++n;
                    }
                    if(n == N+1)
                        return;
                }
                colFrom = 0;
            }
            
            solved = true;
            for(int i = 0; i< N; i++)
            {
                for(int j = 0; j< N; j++)
                    System.out.print(board[i][j] + ",");
                System.out.println();
            }
            System.out.println("==============");
        }
        
        private static boolean isValid(char[][] board, int row, int col, char val)
        {
            for(int c = 0; c<N; ++c)
                if(board[row][c] == val)
                    return false;
            
            for(int r = 0; r<N; ++r)
                if(board[r][col] == val)
                    return false;
            
            int rr = row/s;
            int cc = col/s;
            for(int r = rr*s; r<rr*s+s; ++r)
                for(int c = cc*s; c<cc*s+s; ++c)
                    if(board[r][c] == val)
                        return false;
                        
            return true;
        }

 

Sudoku

原文:http://www.cnblogs.com/neweracoding/p/4230166.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!