poj 1915 BFS 利用 pre 計算步數------------------路徑

來源:互聯網
上載者:User

標籤:style   blog   color   io   for   div   amp   log   

// BFS#include <stdio.h>#include <string.h>int visited[301][301];                               //   visited 已經訪問過了int dic[8][2]={{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2},{1,-2},{2,-1}};int head,end,n,ex,ey,sx,sy;struct quene{    int x,y,pre;                                       // pre 前一個結點}q[100000];void bfs(){    int xx,yy;    head=0;                                               //隊頭  下標為0的元素  第一個 head     end=1;                                            // 下一次要放的元素    q[end].pre=0;             //要放的元素 de 前一個結點 即、
q[end].x=sx; q[end].y=sy; visited[sx][sy]=1; while (head<end) { head++; // 開始往下邊走 head++ for (int i=0;i<8;i++) { xx=q[head].x+dic[i][0]; yy=q[head].y+dic[i][1]; if (xx>=0&&xx<n&&yy>=0&&yy<n&&visited[xx][yy]==0) { end++; q[end].x=xx; q[end].y=yy; q[end].pre=head; visited[xx][yy]=1; if (xx==ex&&yy==ey) return; } } }}void getflo(){ int floor=0; while (q[end].pre!=0) // 倒回去 因為 保留了路徑 { floor++; end=q[end].pre; } printf("%d\n",floor);}int main(){ int ncase; scanf("%d",&ncase); while (ncase--) { memset(visited,0,sizeof(visited)); //memset(q,0,sizeof(q)); scanf("%d",&n); scanf("%d %d",&sx,&sy); scanf("%d %d",&ex,&ey); if (sx==ex&&sy==ey) { printf("0\n"); continue; } else { bfs(); getflo(); } } 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.