首页 > 代码库 > Sudoku

Sudoku

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