经典广搜题

       58-最少步数 

内存限制:64MB
时间限制:3000ms
特判: No
难度:4

题目描述
这有一个迷宫,有08行和08列:
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
入代码片
#include<stdio.h>
#include
#include<string.h>
#include
#include
using namespace std;
int dis[4][2]= {1,0,-1,0,0,1,0,-1};
struct point
{
int x,y,tenp;
};
int bfs(point s,point e,int map[9][9])//
{
queueq;//栈
int i;
point t;
s.tenp=0;//初始步数
map[s.x][s.y]=1;//图开始的搜索;
q.push(s);
while(!q.empty())//栈的模板
{
s=q.front();
q.pop();
if(s.xe.x&&s.ye.y)//判为不能通过或者达到目标;
return s.tenp;//返回步数
for(i=0; i<4; i++)//遍历四个方向
{
t.x=s.x+dis[i][0];
t.y=s.y+dis[i][1];
if(map[t.x][t.y]==0)
{
t.tenp=s.tenp+1;
map[t.x][t.y]=1;
q.push(t);
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t–)
{
point s,e;
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,
};
scanf("%d%d%d%d",&s.x,&s.y,&e.x,&e.y);
printf("%d\n",bfs(s,e,map));
}
return 0;
}




猜你喜欢

转载自blog.csdn.net/qq_43516113/article/details/85247203