HDU 1372 (BFS)

BFS:

起点入队;

开始搜索:

读取队首并出队,搜索范围有四周八个点(有的不存在),搜索到的点入队,并将歩长+1;直到读取的点等于终点;

15MS372K

code:

#include <iostream>
#include <string>
#include <cstdio>
#include <queue>
using namespace std;

struct point
{
	int x;
	int y;
	int step;
}st,ed;
int x1,y1,x2,y2;
bool visit[10][10];
int xx[8] = {1,2,1,2,-1,-2,-1,-2};
int yy[8] = {2,1,-2,-1,2,1,-2,-1};

void bfs()
{
	memset(visit,false,sizeof(visit));
	st.x = x1;
	st.y = y1;
	st.step = 0;
	queue <point> p;
	p.push(st);
	while(!p.empty())
	{
		ed = p.front();
		p.pop();
		if(ed.x == x2 && ed.y == y2)
			break;
		for(int i = 0; i < 8; i++)
		{
			st.x = ed.x + xx[i];
			st.y = ed.y + yy[i];
			st.step = ed.step + 1;
			if(!visit[st.x][st.y]&&st.x>0&&st.x<9&&st.y>0&&st.y<9)
			{
				visit[st.x][st.y] = true;
				p.push(st);
			}
		}
	}
}
int main()
{
	char c1,c2,c;
	while(scanf("%c%d%c%c%d",&c1,&y1,&c,&c2,&y2)!=EOF)
	{
		x1 = c1 - 'a' + 1;
		x2 = c2 - 'a' + 1;
		bfs();
		printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,y1,c2,y2,ed.step);
		getchar();
	}
}


DFS:

由起点对每个点进行周围8个方位访问,递归调用DFS; 复杂度较高;本题只有8*8,所以能接受;

375MS332K

code:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <iomanip>
using namespace std;

int r[8][2]={{2,1},{1,2},{-1,2},{-2,1},
		 {2,-1},{1,-2},{-1,-2},{-2,-1} };
int num[10][10];
void dfs(int x1, int y1, int move)
{
	if(x1<=0 || x1>=9 || y1<=0 || y1>=9||move>=num[x1][y1])
		return ;
	num[x1][y1] = move;
	for(int i = 0; i < 8; i++)
	{
			dfs(x1+r[i][0], y1+r[i][1],move+1);
	}
}

int main(int argc, char *argv[])
{
	int x1,y1,x2,y2;
	char c1,c2,c;
	while(scanf("%c%d%c%c%d",&c1,&y1,&c,&c2,&y2)!=EOF)
	{
		x1 = c1 - 'a' + 1;
		x2 = c2 - 'a' + 1;
		memset(num,100,sizeof(num));
		dfs(x1,y1,0);
		printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,y1,c2,y2,num[x2][y2]);
		getchar();
	}
	return 0;
}



转载于:https://www.cnblogs.com/i-fuqiang/archive/2013/05/06/3189480.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值