UVA439

题意:移动棋子到指定的位置所需要的步数最少,也就是走日字

思路:DFS就是从初始位置进行搜索,每进行一次就更新一次最少步数。

            BFS就是从八个方向搜索,一搜索到指定的位置就返回步数


BFS的代码:

#include<stdio.h>
#include<string.h>

int dx[] = {-1, -1, -2, -2, 1, 1, 2, 2};
int dy[] = {-2, 2, -1, 1, -2, 2, -1, 1};
int x1, y1, x2, y2;
int num;

typedef struct knight{

	int x, y, d;

};

void bfs(int x, int y){
	
	int vis[100][100];	
	knight q[100];
	int front = 0, near = 1;	
	memset(vis, 0, sizeof(vis));	
	memset(q, 0, sizeof(q));	
	q[0].x = x;
	q[0].y = y;
	q[0].d = 0;
	vis[x][y] = 1;	
	while(front < near){
	
		for(int i = 0; i < 8; i++){
				
			int tx = q[front].x + dx[i];			
			int ty = q[front].y + dy[i];	
		
			if(tx >= 0 && tx < 8 && ty >= 0 && ty < 8 && !vis[tx][ty]){
				if(tx == x2 && ty == y2)	
				{
					num = q[front].d + 1;	
					return;	
				}	
			
			vis[tx][ty] = 1;	
			q[near].x = tx;
			q[near].y = ty;
			q[near].d = q[front].d + 1;	
			near++;	
			
			}	
		}	
	
	front++;		
	}
				
}

int main(){

	char c1, c2, c3, c4;	
	while(scanf("%c%c %c%c", &c1, &c2, &c3, &c4) != EOF){
			
		getchar();		
		x1 = c1 - 'a';	
		y1 = c2 - '1';	
		x2 = c3 - 'a';	
		y2 = c4 - '1';	
		num = 0;	
		if(x1 != x2 || y1 != y2)		
			bfs(x1, y1);
		
		printf("To get from %c%c to %c%c takes %d knight moves.\n", c1, c2, c3, c4, num);	
	}
		
	return 0;
}
	
	


	
	
			
				
				
					
			
			
		
















DFS的代码:

#include<stdio.h>
#include<string.h>

int map[10][10];
int dx[] = {-1, -1, -2, -2, 1, 1, 2, 2};
int dy[] = {-2, 2, -1, 1, -2, 2, -1, 1};

void dfs(int x, int y, int t){
	if(x > 7 || x < 0 || y > 7 || y < 0 || map[x][y] <= t)
		return;	
	
	map[x][y] = t;	
	
	for(int i = 0; i < 8; i++)	
	{
		int tx = x + dx[i];	
		int ty = y + dy[i];	
		dfs(tx, ty, t + 1);	
	}
}

int main(){

	char c1, c2, c3, c4;	
	while(scanf("%c%c %c%c", &c1, &c2, &c3, &c4) != EOF){
			
		getchar();	
		int x1, x2, y1, y2;	
		x1 = c1 - 'a';	
		y1 = c2 - '1';	
		x2 = c3 - 'a';	
		y2 = c4 - '1';	
				
		for(int i = 0; i < 8; i++)	
			for(int j = 0; j < 8; j++)	
				map[i][j] = 20;	
		dfs(x1, y1, 0);		
		printf("To get from %c%c to %c%c takes %d knight moves.\n", c1, c2, c3, c4, map[x2][y2]);	
	}
		
	return 0;
}
	
	


	
	
			
				
				
					
			
			
		

















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值