心胸决定格局,眼界决定境界...

8皇后问题

typedef struct Spoint
{
	int x;
	int y;
	Spoint()
	{
		x = -1;
		y = -1;
	}
};

static Spoint point[8];


int Queen8(int n, int cur)
{

	static  int iCount = 0;
	if(cur == n)
	{   
		iCount++;

		for(int i = 0; i < n; i++)
		{
			printf("(%d,%d) ", point[i].x, point[i].y);

		}

		printf("\n");
	}
	else
	{
		for(int i = 0; i < n; i++)
		{
			bool bNextRow = false;
			for(int j = 0; j < n; j++)
			{
					int bShow = false;	

					for(int k = 0; k < cur; k++)
					{
						if(i == point[k].x )
						{
							bNextRow = true;
							break;
						}	
												
						if(j == point[k].y ||
							(i < point[k].x)||  
							(i == point[k].x - 1 && j == point[k].y - 1)||(i == point[k].x - 1 && j == point[k].y + 1)|| \
							(i == point[k].x + 1 && j == point[k].y - 1)||(i == point[k].x + 1 && j == point[k].y + 1))
						{
							bShow = true;
							break;
						}
						
						
					}

					if(bNextRow)
					{
						bNextRow = false;
						break;
					}

					if(!bShow)
					{
						bShow = false;
						point[cur].x = i;
						point[cur].y = j;
						Queen8(n, cur + 1);
					}
			
			}

		}
	}
	return iCount;
}

int WQueen8()
{
	int cur = 0;
	int n = 8;
	
	int *B = (int *)malloc(n * n * sizeof(int));
	memset(B, 0, n * n * sizeof(int));	 

	int num = Queen8(n, cur);
	delete [] B;
	return num;
}

  

posted @ 2014-08-28 11:04  WELEN  阅读(342)  评论(0编辑  收藏  举报