关闭

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

标签: struct
730人阅读 评论(0) 收藏 举报
分类:

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:370356次
    • 积分:7826
    • 等级:
    • 排名:第2652名
    • 原创:426篇
    • 转载:6篇
    • 译文:1篇
    • 评论:18条
    最新评论