您的位置:首页 > 其它

最少步数 南阳oj 58【DFS||BFS】

2015-08-06 11:20 405 查看
描述

这有一个迷宫,有0~8行和0~8列:

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

0表示道路,1表示墙。

现在输入一个道路的坐标作为起点,再如输入一个道路的坐标作为终点,问最少走几步才能从起点到达终点?

(注:一步是指从一坐标点走到其上下左右相邻坐标点,如:从(3,1)到(4,1)。)

输入第一行输入一个整数n(0<n<=100),表示有n组测试数据;

随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。
输出输出最少走几步。
样例输入
2
3 1  5 7
3 1  6 7


样例输出
12
11


//dfs

#include<stdio.h>
int map[][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 ex,ey;
int min;
int dx[4]={0,1,-1,0};
int dy[4]={1,0,0,-1};
void DFS(int x,int y,int cnt)
{
	if(x==ex&&y==ey)
	{
		if(min>cnt) min=cnt;
	}
	if(map[x][y]||cnt+1>min) return ; 
	for(int i=0;i<4;++i)
	{
		int fx=x+dx[i];
		int fy=y+dy[i];
		map[x][y]=1;
		DFS(fx,fy,cnt+1);
		map[x][y]=0;//其他路径也需要走这个点 
	}
}
int main()
{
	int T;
	int sx,sy;
	scanf("%d",&T);
	while(T--)
	{
		min=1900;
		scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
		if(sx==ex&&sy==ey)
		{
			printf("0\n");
			continue;
		}
		DFS(sx,sy,0);
		printf("%d\n",min);
	}
	return 0;
}


//BFS

#include<cstdio>
#include<queue>
#include<cstring>
#define INF 0x3f3f3ff
using namespace std;
int map[][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};
struct walk
{
	int x,y,step;
	friend bool operator <(walk a,walk b)
	{
		return a.step>b.step;
	}
}temp,a;

int ex,ey;
int sx,sy;
int dx[]={0,1,-1,0};
int dy[]={1,0,0,-1};
int min_step;
bool vis[12][12];
bool judge(walk a)
{
	if(vis[a.x][a.y] || a.x>=9 || a.x<0 || a.y>=9 || a.y<0 || map[a.x][a.y]) 
		return 0;
	if(temp.step>=min_step) return 0;
	return 1;
}
void BFS(int x,int y)
{
	priority_queue<walk>q;
	memset(vis,0,sizeof(vis));
	temp.x=x;
	temp.y=y;
	temp.step=0;
	q.push(temp);
	vis[x][y]=1;
	while(!q.empty())
	{
		a=q.top();
		q.pop();
		for(int i=0;i<4;++i)
		{
			temp.x=a.x+dx[i];
			temp.y=a.y+dy[i];
			temp.step=a.step+1;
			if(judge(temp))
			{
				if(temp.x==ex&&temp.y==ey)
				{
					min_step=temp.step;//a.step是队列中最小的步数,当step+1到终点时,这个就是最小步数 
					return ;
				}
				vis[temp.x][temp.y]=1;
				q.push(temp);
			}
		}
	}
}
int main()
{
	int T;
	int sx,sy;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
		if(sx==ex&&sy==ey)
		{
			printf("0\n");
			continue;
		}
		min_step=INF;
		BFS(sx,sy);
		printf("%d\n",min_step); 
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: