BUPT-DSA 2019 Fall Chap.3 騎士遍歷問題

如果只是找一組解,使用bfs就足夠了,dfs會找出所有的解。
bfs之後再寫。
依次輸入地圖矩陣的階數,出發點的x,y(自然座標,從1開始數)。

#include <cstdio>
#define MAX 100

int n;
int solution_cnt;
int offset[][2]={
	{-2,1},
	{-1,2},
	{1,2},
	{2,-1},
	{1,-2},
	{2,1},
	{-2,-1},
	{-1,-2}
};
int map[MAX][MAX];

typedef struct _coor
{
	int x;
	int y;
}Coor;

void dfs(int x,int y,int step)
{
	int i,j,k;
	int tx,ty;
	//如果已經全部遍歷一遍,則開始打印
	bool isFinished=1;
	for(i=0;isFinished && i<n;++i)
		for(j=0;isFinished && j<n;++j)
			if(!map[i][j])
				isFinished=0;
	if(isFinished)
	{
		printf("Solution #%d\n",solution_cnt++ );
		for(i=0;i<n;++i)
			for(j=0;j<n;++j)
				printf("%2d%c",map[i][j],j==n-1?'\n':' ' );
		putchar('\n');
		return ;
	}

	//不然開始嘗試所有位置
	for(k=0;k<8;++k)
	{
		tx=x+offset[k][0];
		ty=y+offset[k][1];
		if(tx<0 || ty<0 || tx>=n || ty>=n) continue;
		if(map[tx][ty]) continue;

		map[tx][ty]=step;
		dfs(tx,ty,step+1);
		map[tx][ty]=0;
	}
}

int main(int argc, char const *argv[])
{
	printf("Key in the degree,start_x and start_y\n");
	scanf("%d",&n);
	int srcx,srcy;
	scanf("%d%d",&srcx,&srcy);
	srcx--;srcy--;
	if(srcx<0 || srcy<0 || srcx>=n || srcy>=n){
			printf("The data isn't rational. Computation terminated.\n");
			return 0;
		}
	map[srcx][srcy]=1;
	dfs(srcx,srcy,2);	
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章