您的位置:首页 > 其它

递归穷举数独终盘

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);
		
		
		
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: