最少步数 (bfs最短路径)

来源:互联网 发布:阿里云概念股创业板 编辑:程序博客网 时间:2024/04/28 15:58

描述

这有一个迷宫,有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)分别表示起点的行、列,终点的行、列。
输出
输出最少走几步。
样例输入
23 1  5 73 1  6 7
样例输出
1211

思路:

       上午学习的广搜 http://blog.csdn.net/qq_36238595/article/details/54945270

这题就是经典的广搜题了

代码:

#include<iostream>#include<algorithm>#include<queue>#include<string.h>using namespace std;int dir[4][2]={-1,0,1,0,0,-1,0,1};int v[9][9]={0};int mg[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}; struct st { int x,y,c; };//queue<struct st> q; //如果是在外面创建队列则在下面操作的时候,每次要清空队列,以免下一组测试用例错误获取队头元素  void copy() { int i,j; for (i=0;i<9;i++) for (j=0;j<9;j++)  v[i][j]=mg[i][j];   }  int bfs(struct st s, struct st e) { queue<struct st> q; int i,j; struct st t;  s.c=0; v[s.x][s.y]=1; q.push(s); while (!q.empty()) {    s=q.front();    q.pop(); if (s.x==e.x&&s.y==e.y) { //while (!q.empty()) //{ //q.pop();// } return s.c; } for (i=0;i<4;i++) { t.x = s.x+dir[i][0]; t.y = s.y+dir[i][1]; //if (t.x<0||t.x>=9||t.y<0||t.y>=9||v[t.x][t.y]==1) // continue; if (v[t.x][t.y]==0) { t.c = s.c+1;     v[t.x][t.y]=1; q.push(t); } } } } int main() { int n;struct st s,e; cin>>n; while (n--) { //memset(v,0,sizeof(v));  copy();     cin>>s.x>>s.y>>e.x>>e.y;     cout<<bfs(s,e)<<endl; } return 0; }


0 0