水題B
阿新 • • 發佈:2018-11-13
國際象棋的棋盤是黑白相間的8 * 8的方格,棋子放在格子中間。如下圖所示:
王、後、車、象的走子規則如下:
- 王:橫、直、斜都可以走,但每步限走一格。
- 後:橫、直、斜都可以走,每步格數不受限制。
- 車:橫、豎均可以走,不能斜走,格數不限。
- 象:只能斜走,格數不限。
寫一個程式,給定起始位置和目標位置,計算王、後、車、象從起始位置走到目標位置所需的最少步數。
Input第一行是測試資料的組數t(0 <= t <= 20)。以下每行是一組測試資料,每組包括棋盤上的兩個位置,第一個是起始位置,第二個是目標位置。位置用"字母-數字"的形式表示,字母從"a"到"h",數字從"1"到"8"。
Output對輸入的每組測試資料,輸出王、後、車、象所需的最少步數。如果無法到達,就輸出"Inf".Sample Input
2 a1 c3 f5 f8
Sample Output
2 1 2 1 3 1 1 Inf
思路:算好橫縱距離,每一種棋子用它的方法來處理。細節看註釋。
#include <bits/stdc++.h> using namespace std; int cmp(int x, int y){ if(x>y) return x; else return y; } int main(){ int t; cin>>t; while(t--){ string a,b; cin>>a>>b; int x = abs(a[0]-b[0]); //起始位置和終點的橫向距離 int y = abs(a[1]-b[1]); //起始位置和終點的縱向距離 if(!x && !y) { cout<<"0 0 0 0"<<endl; //如果起點和終點是一個位置,輸出0 continue; } //王 cout<<cmp(x,y)<<" ";//大的就是步數。 //後 if(x == y) cout<<1<<" "; //對角,一步到位 else if((!x&&y) || (!y&&x) || x % 2 == y % 2) cout<<1<<" "; //These is a question!!! else cout<<2<<" "; //車 if((!x&&y) || (!y&&x)) cout<<1<<" "; //同列或者同行,需要一步 else cout<<2<<" "; //象 if(x == y) cout<<1<<endl; else if(x%2 == y%2) cout<<2<<endl; else cout<<"Inf"<<endl; } return 0; }