最少步數
- 描述
-
這有一個迷宮,有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<stdio.h> #include<queue> #include<stdlib.h> #include<string.h> using namespace std; struct node { int x; int y; int t; }; queue<node>q; int a[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 k[4][2] = {-1, 0, 0, 1, 1, 0, 0, -1}; //表示上下左右四個方向 int b[9][9]; int e, f, c, d; void bfs(int x, int y); int main() { int n; scanf("%d", &n); while(n--) { memset(b, 0, sizeof(b)); //標記數組 while(!q.empty()) //每次都將隊列清空 q.pop(); scanf("%d%d%d%d", &e, &f, &c, &d); if(e == c && f == d) { printf("0\n"); continue; } bfs(e, f); } return 0; } void bfs(int e, int f) { node s, w; int i; s.x = e; s.y = f; s.t = 0; q.push(s); b[e][f] = 1; while(!q.empty()) { w = q.front(); q.pop(); //首先將第一個出隊列 for(i = 0; i < 4; i++) // 分別判斷四個方向 { s.x = w.x + k[i][0]; s.y = w.y + k[i][1]; s.t = w.t + 1; if(s.x == c && s.y == d) { printf("%d\n", s.t); return ; } if(!b[s.x][s.y] && a[s.x][s.y] == 0) //如果沒有被標記並且有路可走 { b[s.x][s.y] = 1; q.push(s); } } } }