Sudoku

Inefficient Print All/One using recursive(DFS)

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 solutions
                                return; //comment this out to get all sudoku solutions
                            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;
        }

 

For BFS, you don't need a recursive call. Do it using while loop

 

add the empty board to the $stack to initialize.

while($stack is not empty)

{

  $board <- $stack.pop();

  look for the next spot(r,c) to fill in current $board

  if(not found)

    problem solved; return the $board

  if(found)

    figure out all possible numbers to fill current (r,c)

    foreach $number in all these numbers 

      fill $number to (r,c) of $board

      push $board to $stack

}

posted @ 2015-01-17 10:08  新一代的天皇巨星  阅读(254)  评论(0)    收藏  举报