跳馬問題(演算法作業)
阿新 • • 發佈:2018-11-08
#
###輸入
輸入有若干測試資料。
每組測試資料僅1行,每行上有2個方格pos1、pos2,之間用一個空格隔開,每格方格表示棋盤上的一個位置,該位置由表示列的1個字母(a-h)及表示行的一個數字(1-8)構成,如“d7”表示第4列第7行。
###輸出
對輸入中每行上的2個方格pos1、pos2,輸出馬從位置pos1跳到pos2所需的最短路徑長。如“a1==>a2: 3 moves”表示從位置a1跳到a2所需的最少步數是3。
注意:按輸出樣例所示格式輸出,如“a1==>a2: 3 moves”中冒號後有一個空格,再跟著所需的最少步數。
###輸入樣例
a1 a2
a1 a3
a1 h8
g2 b8
###輸出
a1==>a2: 3 moves
a1==>a3: 2 moves
a1==>h8: 6 moves
g2==>b8: 5 moves
##分析:
因為只有8x8的方格,所以考慮bfs搜尋即可。
###執行結果:
###原始碼:
#include <bits/stdc++.h> using namespace std; const int maxn=100; int mp[10][10]; int dx[8]={1,1,2,2,-1,-1,-2,-2},dy[8]={2,-2,1,-1,2,-2,1,-1}; int ex,ey; int ans; bool check(int x,int y) { return x>=1&&x<=8&&y>=1&&y<=8; } void bfs(int x,int y) { int step=0; queue<tuple<int,int,int>> que; que.push(make_tuple(x,y,0)); while(que.empty()==0) { tuple<int,int,int> tmp=que.front(); que.pop(); for(int i=0;i<8;i++) { int nx=get<0>(tmp); int ny=get<1>(tmp); nx+=dx[i],ny+=dy[i]; int st=get<2>(tmp); if(check(nx,ny)) { que.push(make_tuple(nx,ny,get<2>(tmp)+1)); if(nx==ex&&ny==ey) { ans=st+1; return; } } } } } string s1,s2; int main() { #ifndef ONLINE_JUDGE freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); #endif while(cin>>s1>>s2) { int sx=s1[0]-'a'+1; int sy=s1[1]-'0'; ex=s2[0]-'a'+1,ey=s2[1]-'0'; bfs(sx,sy); cout<<s1<<"==>"<<s2<<": "<<ans<<"moves"<<endl; } return 0; }
實驗體會
本次實驗非常簡單,直接bfs爆力搜尋即可。