搜尋——Knight Moves
阿新 • • 發佈:2019-01-30
問題 Z: Knight Moves
時間限制: 1 Sec 記憶體限制: 128 MB
提交: 23 解決: 22
[提交][狀態][討論版][命題人:quanxing]
題目描述
輸入n代表有個n*n的棋盤,輸入開始位置的座標和結束位置的座標,問一個騎士朝棋盤的八個方向走馬字步,從開始座標到結束座標可以經過多少步。
輸入
首先輸入一個n,表示測試樣例的個數。
每個測試樣例有三行。
第一行是棋盤的大小L(4≤L≤300);
第二行和第三行分別表示馬的起始位置和目標位置(0~L-1)。
輸出
馬移動的最小步數,起始位置和目標位置相同時輸出0。
樣例輸入
3 8 0 0 7 0 100 0 0 30 50 10 1 1 1 1
樣例輸出
5
28
0
#include<iostream> #include<algorithm> #include<cmath> #include<cstdio> #include<cstring> #include<queue> using namespace std; int n,sx,sy,ex,ey,l,flag,sum1; int dir[8][2]={1,2,2,1,2,-1,1,-2,-1,-2,-2,-1,-1,2,-2,1}; int a[300][300]={0}; struct node { int x; int y; int sum=0; }s,e,temp; int main() { cin>>n; while(n--) { flag=0; queue<node>q; cin>>l; cin>>s.x>>s.y>>e.x>>e.y; memset(a,0,sizeof(a)); q.push(s); temp=q.front(); while(!q.empty()) { temp=q.front(); sum1=temp.sum; q.pop(); if(temp.x==e.x&&temp.y==e.y) break; for(int i=0;i<8;i++) { temp.x+=dir[i][0]; temp.y+=dir[i][1]; if(!a[temp.x][temp.y]&&temp.x>=0&&temp.x<l&&temp.y>=0&&temp.y<l) { a[temp.x][temp.y]=1; temp.sum=sum1+1; q.push(temp); } temp.x-=dir[i][0]; temp.y-=dir[i][1]; } } cout<<temp.sum<<endl; } return 0; }