最少步数
时间限制: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,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<iostream>
#include<iomanip>
#include<algorithm>
#include<cstring>
#include<sstream>
#include<cmath>
#include<queue>
#define NUM 666
struct location{
int row;
int col;
};
using namespace std;
int map[10][10], roaded[10][10];
int a,b,c,d;
queue<location> nowroad;
int bfs(){
location temploc, nowloc;
while(!nowroad.empty())
nowroad.pop();
temploc.row=a;
temploc.col=b;
nowroad.push(temploc);
while(!nowroad.empty()){
nowloc=nowroad.front();
nowroad.pop();
if(nowloc.row==c && nowloc.col==d)
return roaded[nowloc.row][nowloc.col];
//上下左右
if(nowloc.row-1>=0 && map[nowloc.row-1][nowloc.col]==0){
roaded[nowloc.row-1][nowloc.col]=roaded[nowloc.row][nowloc.col]+1;
temploc.row=nowloc.row-1;
temploc.col=nowloc.col;
nowroad.push(temploc);
}
if(nowloc.row+1<9 && map[nowloc.row+1][nowloc.col]==0){
roaded[nowloc.row+1][nowloc.col]=roaded[nowloc.row][nowloc.col]+1;
temploc.row=nowloc.row+1;
temploc.col=nowloc.col;
nowroad.push(temploc);
}
if(nowloc.col-1>=0 && map[nowloc.row][nowloc.col-1]==0){
roaded[nowloc.row][nowloc.col-1]=roaded[nowloc.row][nowloc.col]+1;
temploc.row=nowloc.row;
temploc.col=nowloc.col-1;
nowroad.push(temploc);
}
if(nowloc.col+1<9 && map[nowloc.row][nowloc.col+1]==0){
roaded[nowloc.row][nowloc.col+1]=roaded[nowloc.row][nowloc.col]+1;
temploc.row=nowloc.row;
temploc.col=nowloc.col+1;
nowroad.push(temploc);
}
}
return 0;
}
int main()
{
int T,i,j;
freopen("in.txt","r",stdin);
for(i=0; i<9; i++)
for(j=0; j<9; j++)
scanf("%d",&map[i][j]);
scanf("%d",&T);
while(T--){
scanf("%d%d%d%d",&a,&b,&c,&d);
memset(roaded, -1, sizeof(roaded));
roaded[a][b]=0;
printf("%d\n",bfs());
}
fclose(stdin);
return 0;
}
附件:in.txt
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
2
3 1 5 7
3 1 6 7