http://acm.nyist.net/JudgeOnline/problem.php?pid=58

bfs搜索水题进行时~~~~

#include<iostream>
#include<string.h>
#include<cstdio>
#include<string>
#include<queue>
using namespace std;
int map[9][9]=
{1,1,1,1,1,1,1,1,1,
 1,0,0,1,0,0,1,0,1,
 1,0,0,1,1,0,0,0,1,
 1,0,1,0,1,1,0,1,1,
 1,0,0,0,0,1,0,0,1,
 1,1,0,1,0,1,0,0,1,
 1,1,0,1,0,1,0,0,1,
 1,1,0,1,0,0,0,0,1,
 1,1,1,1,1,1,1,1,1
};
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
struct point
{
	int x;
	int y;
	int step;
}po;
bool visit[10][10];
int sx,sy,ex,ey;
int step;
int bfs(int x,int y)
{
	memset(visit,false,sizeof(visit));
	queue<point>q;
	po.x=x;po.y=y;po.step=0;
	q.push(po);
	visit[x][y]=true;
	while(!q.empty())
	{
		po=q.front();
		q.pop();
		x=po.x;y=po.y;step=po.step;
		if(x==ex&&y==ey) return step;
		for(int i=0;i<4;++i)
		{
			int x1=x+dx[i];
			int y1=y+dy[i];
			if(!map[x1][y1]&&!visit[x1][y1]&&x1>=0&&x1<=8&&y1>=0&&y1<=8)
			{ po.x=x1;po.y=y1;po.step=step+1;q.push(po);
			  visit[x1][y1]=true;
			}
		}
	}
}
int main()
{
	int T;
	cin>>T;
	while(T--)
	{
		cin>>sx>>sy>>ex>>ey;
		cout<<bfs(sx,sy)<<endl;
	}return 0;
}

dfs

#include<iostream>
#include<string.h>
#include<cstdio>
#include<string>
#include<queue>
using namespace std;
int map[9][9]=
{1,1,1,1,1,1,1,1,1,
 1,0,0,1,0,0,1,0,1,
 1,0,0,1,1,0,0,0,1,
 1,0,1,0,1,1,0,1,1,
 1,0,0,0,0,1,0,0,1,
 1,1,0,1,0,1,0,0,1,
 1,1,0,1,0,1,0,0,1,
 1,1,0,1,0,0,0,0,1,
 1,1,1,1,1,1,1,1,1
};
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
struct point
{
	int x;
	int y;
	int step;
}po;
int sx,sy,ex,ey;
int step,minstep;
void dfs(int x,int y)
{
	if(x==ex&&y==ey) {minstep=min(step,minstep);return;}//结束条件
	 for(int i=0;i<4;++i)
	{
		int x1=dx[i]+x;
		int y1=dy[i]+y;
		if(x1>=0&&x1<=8&&y1>=0&&y1<=8&&!map[x1][y1])
		{
			step++;
			map[x1][y1]=1;
			dfs(x1,y1);
			map[x1][y1]=0;//回溯。。。。
			step--;
		}
	}
}
int main()
{
	int T;
    scanf("%d",&T);
	while(T--)
	{    step=0;
	     minstep=0xffffff;
		scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
		map[sx][sy]=1;
		dfs(sx,sy);
		map[sx][sy]=0;
		printf("%d\n",minstep);
	}return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值