POJ - 1915 Knight Moves

來源:互聯網
上載者:User

標籤:os   art   io   for   cti   re   

BFS結合隊列

#include<stdio.h>#include<string.h>#include<queue>using namespace std;int x,y,l;const int maxn=300+5;int visit[maxn][maxn];struct node{    int xpos;    int ypos;    int cur;    void init(int x,int y,int d)    {    xpos=x;ypos=y;cur=d;    }};int bfs(node source,node target);int main(){    int n;    scanf("%d",&n);    while(n--){        scanf("%d",&l);        node start;        node end;        scanf("%d%d",&start.xpos,&start.ypos);        scanf("%d%d",&end.xpos,&end.ypos);        int minsteps=bfs(start,end);        printf("%d\n",minsteps);    }    return 0;}int bfs(node source,node target){    int dir[10][5]={{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2}};    source.cur=0;    queue<node>temp;    temp.push(source);    memset(visit,0,sizeof(visit));    visit[source.xpos][source.ypos]=1;    if(source.xpos==target.xpos && source.ypos==target.ypos)        return 0;    while(!temp.empty()){        node c=temp.front();        x=c.xpos;        y=c.ypos;        for(int i=0;i<8;i++){            int midx=x+dir[i][0];            int midy=y+dir[i][1];            if(midx<0 || midx>=l || midy<0 || midy>=l)                continue;            if(visit[midx][midy])                continue;            if(midx==target.xpos && midy==target.ypos)                return c.cur+1;            visit[midx][midy]=1;            node a;            a.init(midx,midy,c.cur+1);            temp.push(a);        }        source.cur++;        temp.pop();    }    return -1;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.