http://acm.nyist.net/JudgeOnline/problem.php?pid=58
最少步数
时间限制:
3000 ms | 内存限制:
65535 KB
难度:
4
-
描述
-
这有一个迷宫,有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,10表示道路,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
-
第一行输入一个整数n(0<n<=100),表示有n组测试数据;
#include<stdio.h>
#include<string.h>
#include<queue>
#include <algorithm>
using namespace std;
struct Seat
{//位置
int x;
int y;
};
int main()
{
int graph[][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},
},
judge[9][9],
dir[4][2]={
{0,-1},{0,1},{-1,0},{1,0},//上下左右
};
int N,x,y,a,b,c,d,i,j;
scanf("%d",&N);
while(N--)
{
scanf("%d %d %d %d",&a,&b,&c,&d);
memset(judge,0,sizeof(judge));
queue<Seat>Q;
struct Seat num;
num.x=a;num.y=b;
Q.push(num);
judge[a][b]=1;
while(!Q.empty())
{
num=Q.front();
Q.pop();
for(i=0;i<4;i++)
{
x=num.x+dir[i][0];
y=num.y+dir[i][1];
if(x<=0||x>=8||y<=0||y>=8||graph[x][y]==1||judge[x][y]!=0) continue;
if(judge[x][y]==0)
{
judge[x][y]=judge[num.x][num.y]+1;
struct Seat p;
p.x=x;p.y=y;
Q.push(p);
}
}
}
// for(i=0;i<9;i++)
// {
// for(j=0;j<9;j++)
// printf("%d ",judge[i][j]);
//
// printf("\n");
// }
printf("%d\n",judge[c][d]-1);
}
return 0;
}

本文介绍了一种解决迷宫寻路问题的算法,通过输入起点和终点坐标,计算最少步数达到终点。使用广度优先搜索算法遍历迷宫,优化路径查找效率。
834

被折叠的 条评论
为什么被折叠?



