南陽理工58最少步數
阿新 • • 發佈:2019-02-15
最少步數
時間限制: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,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
來源
[苗棟棟]原創
上傳者
苗棟棟
時間限制: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,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
來源
[苗棟棟]原創
上傳者
苗棟棟
題意分析:這是最簡單的搜尋問題,用的是BFS,唯一注意的一點就是,當輸入為兩個點相等時,應該輸出為0
#include<iostream> #include<stdio.h> #include<queue> using namespace std; int dx[]={1,0,0,-1}; int dy[]={0,1,-1,0}; struct dot { int x,y; int time; }; inline bool in(dot gx) { if(gx.x>=0&&gx.x<9&&gx.y>=0&&gx.y<9) return true; return false; } int main() { int vis[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 test; int x1,x2,y1,y2; cin>>test; while(test--) { dot gx; cin>>x1>>y1>>x2>>y2; if(x1==x2&&y1==y2) cout<<0<<endl; else { gx.x=x1; gx.y=y1; gx.time=0; queue<dot>q; while(!q.empty()) q.pop(); q.push(gx); int step=0; while(!q.empty()) { dot next,tmp; tmp=q.front(),q.pop(); for(int i=0;i<4;i++) { next.x=tmp.x+dx[i]; next.y=tmp.y+dy[i]; next.time=tmp.time+1; if(in(next)&&!vis[next.x][next.y]) { q.push(next); if(next.x==x2&&next.y==y2) { step=next.time; break; } } } if(step>0) break; } cout<<step<<endl; } } return 0; }