<span style="color: rgb(70, 70, 70); font-family: Tahoma, Arial, sans-serif, simsun; font-size: 14px; background-color: rgb(255, 255, 255);">時間限制:</span><span class="editable highlight" id="problem[time_limit]" style="font-family: Tahoma, Arial, sans-serif, simsun; font-size: 14px; background-color: rgb(255, 255, 255);">3000</span><span style="color: rgb(70, 70, 70); font-family: Tahoma, Arial, sans-serif, simsun; font-size: 14px; background-color: rgb(255, 255, 255);"> ms | 內存限制:</span><span class="editable highlight" id="problem[memory_limit]" style="font-family: Tahoma, Arial, sans-serif, simsun; font-size: 14px; background-color: rgb(255, 255, 255);">65535</span><span style="color: rgb(70, 70, 70); font-family: Tahoma, Arial, sans-serif, simsun; font-size: 14px; background-color: rgb(255, 255, 255);"> KB</span>
- 描述
-
這有一個迷宮,有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<cstring> #include<queue> using namespace std; 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 x1,y1,x2,y2,k; int vis[8][8]; int a[4]={-1,1,0,0}; int b[4]={0,0,-1,1}; struct node{ int x,y; int step; }; queue<node> Q; int bfs(int x1,int y1,int x2,int y2) { int i,s,t; node e={x1,y1,0}; Q.push(e); vis[x1][y1]=1; while(!Q.empty()) { e=Q.front(); if(e.x==x2&&e.y==y2) { break; } Q.pop(); for(i=0;i<4;i++) { s=e.x+a[i]; t=e.y+b[i]; if(s>=0&&s<=8&&t>=0&&t<=8&&!vis[s][t]&&map[s][t]==0) { node e1={s,t,e.step+1}; Q.push(e1); vis[s][t]=1; } } } if(Q.empty()) { return -1; } while(!Q.empty()) { Q.pop(); } return e.step; } int main() { int t; cin>>t; while(t--) { cin>>x1>>y1>>x2>>y2; memset(vis,0,sizeof(vis)); k=bfs(x1,y1,x2,y2); cout<<k<<endl; } return 0; }