U E D R , A S I H C RSS

Eight Queen Problem/임인택/java

심심해서 자바코드로 그냥 옮겼습니다. 몇군데만 수정하니까 그대로 돌아가는군요~ 호호..-.-;;

~cpp 
import java.util.*;

class Queen
{
	int QUEEN;
	int Queen[][];

	Queen(int noq)
	{
		QUEEN=noq;

		Queen = new int[QUEEN][QUEEN];

		for(int i=0; i<QUEEN; i++)
		{
			reset(0);
			get_Queen(i,0);
		}
	}

	public void get_Queen(int x, int y)
	{
		reset(y+1);
		Queen[x][y]=1;

		if(y==QUEEN-1) print_result();

		for(int i=0; i<QUEEN; i++)
			if(check(i,y+1))
				get_Queen(i,y+1);

		Queen[x][y]=0;
	}

	public void print_result()
	{
		int i,j;

		for(i=0; i<QUEEN; i++)
		{
			for(j=0; j<QUEEN; j++)
				System.out.print(Queen[j][i] + "   ");
			System.out.println();
		}
		
		try{
		Thread.sleep(1000);
		}
		catch(Exception e){}
	}

	public void reset(int fromline)
	{
		int i,j;

		for(i=0; i<QUEEN; i++)
			for(j=fromline; j<QUEEN; j++)
				Queen[i][j]=0;
	}

	public boolean check(int i, int j)
	{
		if(i<0 || j<0 || i>=QUEEN || j>=QUEEN) 
                return false; 
 
		int x, y, sum=0; 
 
		for(y=j-1; y>=0 && sum==0; y--) /* 위로 */ 
			sum+=Queen[i][y]; 
		for(x=i-1; x>=0 && sum==0; x--) /* 왼쪽으로 */ 
			sum+=Queen[x][j]; 
		for(x=i-1, y=j-1; x>=0 && y>=0 && sum==0; x--, y--) /* 대각선 */ 
			sum+=Queen[x][y]; 
		for(x=i+1, y=j-1; x<QUEEN && y>=0 && sum==0; x++, y--) /* 대각선 */ 
			sum+=Queen[x][y]; 
 
		if(sum==0)
			return true;
		else
			return false;
	}
	public static void main(String args[])
	{
		if(args.length!=1)
		{
			System.out.println("ex) java Queen NumofQueens");
			System.exit(0);
		}

		Queen myqueen = new Queen(Integer.parseInt(args[0]));
	}
}
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2009-05-27 07:09:19
Processing time 0.0059 sec