HDU-1372 Knight Moves (BFS)

來源:互聯網
上載者:User

題意:

 就是國際象棋中馬,從某一座標到另一個座標的最小步數(走"日"子格).

好久沒做搜尋題了,估計也忘得差不多了,今天到oj上來涮寫基礎題。幸好這題簡單,一下就A了。

#include<cstdio>#include<queue>#include<cstring>using namespace std;struct node{int x,y,s;};int visit[8][9];int x_add[8]={-2,-2,-1,-1,2,2,1,1};int y_add[8]={-1,1,-2,2,-1,1,-2,2};int x1,y1;bool judge(int x,int y){if (x>=0&&x<8&&y>0&&y<9) return true;else return false;}int BFS(int x,int y){queue<node>Q;node t;t.x=x;t.y=y;t.s=0;    Q.push(t);while(!Q.empty()){t=Q.front();Q.pop();    int x=t.x,y=t.y,s=t.s;if(x==x1&&y==y1) return s;for(int i=0;i<8;i++){   intxx=x+x_add[i];   intyy=y+y_add[i];if(!visit[xx][yy]&&judge(xx,yy)){visit[xx][yy]=1;t.x=xx,t.y=yy,t.s=s+1;Q.push(t);}}}}int main(){char s[3],t[3];int x,y;while(scanf("%s %s",s,t)!=EOF){memset(visit,0,sizeof(visit));x=s[0]-'a';y=s[1]-'0';x1=t[0]-'a';y1=t[1]-'0';printf("To get from %s to %s takes %d knight moves.\n",s,t,BFS(x,y));}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.