最少步数
时间限制:
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组测试数据;
思路分析:考查无权图单源最短路,我用的队列BFS。感觉比别人代码长了好多......
#include <cstdio>
#include <queue>
#define MAX 9
using namespace std;
typedef struct {
int x;
int y;
int level;
} Point;
int MGraph[MAX][MAX] = { { 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 visit[MAX][MAX];
void bfs( Point s, Point e ) {
queue<Point> q;
s.level = 0;
q.push( s );
visit[s.x][s.y] = 1;
Point next;
while( !q.empty() ) {
Point cur = q.front();
q.pop();
if( cur.x == e.x && cur.y == e.y ) {
printf( "%d\n", cur.level );
break;
}
if( !visit[cur.x - 1][cur.y] && !MGraph[cur.x - 1][cur.y] && ( cur.x - 1 >= 0 && cur.x - 1 < MAX ) && ( cur.y >= 0 && cur.y < MAX ) ) {
next.x = cur.x - 1;
next.y = cur.y;
next.level = cur.level + 1;
visit[cur.x - 1][cur.y] = 1;
q.push( next );
}
if( !visit[cur.x + 1][cur.y] && !MGraph[cur.x + 1][cur.y] && ( cur.x + 1 >= 0 && cur.x + 1 < MAX ) && ( cur.y >= 0 && cur.y < MAX ) ) {
next.x = cur.x + 1;
next.y = cur.y;
next.level = cur.level + 1;
visit[cur.x + 1][cur.y] = 1;
q.push( next );
}
if( !visit[cur.x][cur.y - 1] && !MGraph[cur.x][cur.y - 1] && ( cur.x >= 0 && cur.x < MAX ) && ( cur.y - 1 >= 0 && cur.y - 1 < MAX ) ) {
next.x = cur.x;
next.y = cur.y - 1;
next.level = cur.level + 1;
visit[cur.x][cur.y - 1] = 1;
q.push( next );
}
if( !visit[cur.x][cur.y + 1] && !MGraph[cur.x][cur.y + 1] && ( cur.x >= 0 && cur.x < MAX ) && ( cur.y + 1 >= 0 && cur.y + 1 < MAX ) ) {
next.x = cur.x;
next.y = cur.y + 1;
next.level = cur.level + 1;
visit[cur.x][cur.y + 1] = 1;
q.push( next );
}
}
}
int main() {
int n;
Point s;
Point e;
scanf( "%d", &n );
while( n-- ) {
for( int i = 0; i < MAX; i++ ) {
for( int j = 0; j < MAX; j++ ) {
visit[i][j] = 0;
}
}
scanf( "%d%d%d%d", &s.x, &s.y, &e.x, &e.y );
bfs( s, e );
printf( "\n" );
}
return 0;
}