最少步數 (bfs最短路徑)
阿新 • • 發佈:2018-12-25
描述
這有一個迷宮,有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
思路:
上午學習的廣搜 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; }