最少步数
时间限制:
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
#include<iostream> #include<cstdio> #include<cstring> #include<stack> using namespace std; const int INF = 100000000; typedef struct pair{ int x; int y; }p; int d[10][10];//到各个位置最短距离的数组 //4个方向移动的向量 int dx[4]={1,0,-1,0}; int dy[4]={0,1,0,-1}; 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 }; int bfs(p start,p end){ stack<p>que; //把所有的位置都初始化为INF for(int i=0;i<10;i++) for(int j=0;j<10;j++) d[i][j] = INF; que.push(start); d[start.x][start.y]=0; //不断循环直到队列的长度为0 while(que.size()){ //从队列的最前端取出元素并且弹出来 p q =que.top(); //弹出该元素 que.pop(); //如果取出的状态已经是终点则结束搜索 if(q.x==end.x&&q.y==end.y) break; //四个方向的循环 for(int i=0;i<4;i++){ int nx=q.x+dx[i]; int ny=q.y+dy[i]; //判断是否可以移动以及是否访问过的 if(0<=nx&&nx<8&&ny>=0&&ny<8&&map[nx][ny]!=1&&d[nx][ny]==INF){ //可以移动的话则加入队列,并且到该位置的距离等于到p的距离+1 p q1; q1.x=nx; q1.y=ny; que.push(q1); d[nx][ny]=d[q.x][q.y]+1; } } } return d[end.x][end.y]; } int main(){ int n; int a,b,c,d; p start,end; scanf("%d",&n); while(n--){ scanf("%d%d%d%d",&a,&b,&c,&d); start.x=a; start.y=b; end.x=c; end.y=d; int res = bfs(start,end); printf("%d\n",res); } return 0; }
-
第一行输入一个整数n(0<n<=100),表示有n组测试数据;