递归穷举数独终盘
2015-09-25 19:07
387 查看
package cn.itcast; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class Shudu { public static int count=0,countW=0; public static void dfs(int num,int row,int col,int a[][],List<LinkedList<Integer>> RowUsed,List<LinkedList<Integer>> ColUsed,List<LinkedList<Integer>> AreaUsed) { if(col==9||row==num) { if(row==num) { count++; } else { //下一行 dfs(num,row+1,0,a,RowUsed,ColUsed,AreaUsed); } }else { //找出行列小方格都不重复的 for(int i=1;i<=9;i++) { Integer index=new Integer(i); //去掉重复 if(RowUsed.get(row).contains(index)||ColUsed.get(col).contains(index)||AreaUsed.get(3*(row/3)+col/3).contains(index)) { continue; } //去掉对角线为1 if(i==1&&(row==col||row+col==8)) continue; //赋值 a[row][col]=i; //用掉 RowUsed.get(row).add(index); ColUsed.get(col).add(index); AreaUsed.get(3*(row/3)+col/3).add(index); //递归 dfs(num,row,col+1,a,RowUsed,ColUsed,AreaUsed); //恢复 RowUsed.get(row).remove(index); ColUsed.get(col).remove(index); AreaUsed.get(3*(row/3)+col/3).remove(index); } } } public static void print(int a[][]) { for(int i=0;i<9;i++) { for(int j=0;j<9;j++) { System.out.print(a[i][j]+" "); } System.out.println(""); } } public static int count(int b[][],int row,int fixrow) { List<LinkedList<Integer>> RowUsed=new ArrayList<LinkedList<Integer>>(), ColUsed=new ArrayList<LinkedList<Integer>>(), AreaUsed=new ArrayList<LinkedList<Integer>>(); for(int i=0;i<9;i++) { RowUsed.add(new LinkedList<Integer>()); ColUsed.add(new LinkedList<Integer>()); AreaUsed.add(new LinkedList<Integer>()); } for(int r=0;r<fixrow;r++) { for(int i=0;i<9;i++) { RowUsed.get(r).add(b[r][i]); ColUsed.get(i).add(b[r][i]); AreaUsed.get(3*(r/3)+i/3).add(b[r][i]); } } Shudu.dfs(row,fixrow,0, b, RowUsed,ColUsed,AreaUsed); int c=count; count=0; return c; } public static void main(String args[]) { //1 int a[][]=new int[][]{ {2,1,3,4,5,6,7,8,9}, {4,5,6,7,8,9,1,2,3}, {7,8,9,1,2,3,4,5,6}, {1,3,7,9,8,6,2,4,5}, {0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0}}; int b[][]=new int[][]{ {2,3,1,4,5,6,7,8,9}, {4,5,6,7,8,9,1,2,3}, {7,8,9,1,2,3,4,5,6}, {1,3,7,9,8,6,2,4,5}, {0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0}}; int count1=count(a,1,0); System.out.println("第一行排列数:"+count1); //2 int count2=count(b,9,4); System.out.println("固定第一行,第二行排列数:"+count2); } }
相关文章推荐
- 皮尔逊积矩相关系数的学习
- uninstall vs extension
- 使用Serializable和Parcelable实现在activity之间的传输
- eclipse汉化
- HDOJ 题目3415 Max Sum of Max-K-sub-sequence(单调队列求区间和最大值)
- Java基础知识强化95:Calendar类之Calendar类的add()和set()方法
- Java面向对象之内部类
- 派生类的构造函数及析构函数
- 无聊
- C++试题
- Linux开机执行shell命令
- 新手如何搭建spring web工程
- Xcode常用快捷键使用
- 正则表达式全部符号解释
- JTable 表格中添加 JComboBox 控件
- Qrcode生成二维码普通篇之jquery.qrcode.min.js
- UVA 11354 Bond
- 计算机思想的保养
- OC-类的加载和初始化
- Alcatraz 插件添加 (7.0)