Sudoku backtracking with one dimension array

来源:互联网 发布:关于弹钢琴的软件 编辑:程序博客网 时间:2024/06/02 17:13
package hello.test;import java.io.*;import java.util.*;public class Sudoku {private static final int N = 9;  // the size of the boardprivate int[] board;  // the one dimension array that stores board data// constructorpublic Sudoku() {try {init();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}// initprivate void init() throws FileNotFoundException {// TODO Auto-generated method stubboard = new int[N * N];Scanner fin = new Scanner(new File("/home/will/myworld/workspace/HelloProject/src/sudokuin.txt"));int numCases = fin.nextInt();for (int c=1; c<=numCases; c++) {for(int i = 0; i < N * N; i++) {board[i] = fin.nextInt();}}}// solve the problem using backtracking methodpublic void solve(int cell) {if (cell == N * N) { this.show(); return; }// skip over cell n since it has fixed valueif (board[cell] != 0) { solve(cell + 1); return; }// try all 9 possibilitiesfor (int n = 1; n <= N; n++) {if (isConsistent(cell, n)) {board[cell] = n;solve(cell + 1);}}board[cell] = 0; // clean up after itself}// if the cell puts number n, does it conflict in row, column and the small squareprivate boolean isConsistent(int cell, int n) {//if (board[cell] != 0) return false;int R = cell / N;  // the row of the two dimensional arrayint C = cell % N;  // the column of the two dimensional arrayint r = R / 3;   // the small 3 * 3 array's rowint c = C / 3;     // the small 3 * 3 array's column// is the row consistentfor(int i = 0; i < N; i++) {if(board[R * N + i] == n) return false;  // the row of the cell is equal to n}// is the column consistentfor(int j = 0; j < N; j++) {if(board[j * N + C] == n) return false;  // the column of the cell is equal to n}// is the square consistentfor(int i = 0; i < 3; i++) {for(int j = 0; j < 3; j++) {// (3 * r + i) * N + 3 * c + j is the small square's position in one dimensional arrayif(board[(3 * r + i) * N + 3 * c + j] == n) return false;  }}// otherwise, the cell is consistent in row, column and square, return truereturn true;}// show boardpublic void show() {for(int i = 1; i <= N * N; i++) {System.out.print(board[i - 1] + " ");if(i % N == 0) {System.out.println();}}}/** * @param args */public static void main(String[] args) throws Exception {// TODO Auto-generated method stubSudoku s = new Sudoku();s.solve(0);}}


Below is a test case:

 

1
0 8 0 4 0 2 0 6 0
0 3 4 0 0 0 9 1 0
9 6 0 0 0 0 0 8 4
0 0 0 2 1 6 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 3 5 7 0 0 0
8 4 0 0 0 0 0 7 5
0 2 6 0 0 0 1 3 0
0 9 0 7 0 1 0 4 0