日期:2014-05-20  浏览次数:20725 次

一个求解数独的代码,谁能给分析下?
package Java.puzzler;  
import static java.util.Arrays.*;  
  
public class Puzzler{  
  public static final int SIZE =9;  
  private boolean[][] fixed =new boolean[SIZE][SIZE];  
  private int[][] number =new int[SIZE][SIZE];  
  public Puzzler(){  
  }  
  public Puzzler(int[][] p){  
  setPuzzler(p);  
  }  
  /**  
  * 用一个二维数组去设置该数独  
  * 注意:这个二维数组应该只包含0~9中的数字,为0时表示该处留空  
  * 该方法假设p的数据是合法的,不对其进行任何检查  
  */  
  public void setPuzzler(int[][] p){  
  for(int i=0;i<SIZE;i++)  
  for(int j=0;j<SIZE;j++){  
  if(p[i][j] ==0){  
  fixed[i][j] =false; //不固定
  number[i][j] =0; //将 0 装入number数组 
  } else{  
  number[i][j] =p[i][j]; //将用户输入数组装入number数组 
  fixed[i][j] =true; //固定
  }  
  }  
  }  
  /**  
  * 清除  
  */  
  public void clear(){  
  for(int n=0;n<SIZE;n++){  
  fill(fixed[n],false);  
  fill(number[n],0); //fill用法?
  }  
  return;  
  }  
  /**  
  * 位置i,j是否固定,如果固定表示该处的数字不能更改  
  */  
  public boolean isFixed(int i,int j){  
  return fixed[i][j]; //判断是否为空
  }  
  /**  
  * 得到位置i,j处的数字  
  */  
  public int getNumber(int i,int j){  
  return number[i][j];  
  }  
  /**  
  * 设置i,j处的数字.如果该处数字是固定的,将抛出异常  
  */  
  public void setNumber(int i,int j,int num){  
  if(num<0||num>9) throw new IllegalArgumentException("number is out of 0~9 :"+num);  
  if(isFixed(i,j)) throw new IllegalStateException("puzzler("+i+","+j+") is fixed");  
  number[i][j] =num; //将 num 装入number数组
  }  

============================================================================================

import Java.puzzler.*;  
  
/**  
 * 求解Sodoku Puzzler的工具类  
 * @author Eastsun  
 */  
public class Solver{  
  private static final int SIZE = Puzzler.SIZE;  
  private Solver(){  
  }  
  public static boolean solve(Puzzler p){  
  int[][] num =new int[SIZE][SIZE];  
  boolean[][] rFlags =new boolean[SIZE][SIZE+1], //SIZE+1代表用户数字t
  cFlags =new boolean[SIZE][SIZE+1],  
  zFlags =new boolean[SIZE][SIZE+1];  
  for(int r=0;r<SIZE;r++)  
  for(int c=0;c<SIZE;c++)  
  if(p.isFixed(r,c)){ // 排除 0
  int t =p.getNumber(r,c); //得到r,c处的用户数字t
  num[r][c] =t; //并装入num数组
  rFlags[r][t] =true; //r-t
  cFlags[c][t] =true; //c-t
  zFlags[r/3*3+c/3][t] =true; //区域036 147 258