차례차례 궁지에 몰리다

2834 단어
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);
		
		
		
	}
}

좋은 웹페이지 즐겨찾기