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

Sudoku

时间:2015-01-17 11:10:03      阅读:110      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!