PKU 3964 無向圖廣度遍曆

來源:互聯網
上載者:User

題意:已經一個5*5的二維數組,共中0代表可通過,1代表不可。求(0,0)到(4,4)即對角線的最短路,只允許上下左右走。

分析:因為求最短路徑,所以是BFS不可DFS。關鍵在於如何記錄走過路徑,路徑隊列每次加入新節點務必記錄它的前驅節點,遍曆結束後從終點依照前驅節一直找到源點求最短路徑(由源點向終點可能多解,需要處理),然後用輔助棧反序。

 

C/C++源碼:

#include <iostream><br />#include <cstring><br />#include <vector><br />#include <stack><br />#include <queue><br />using namespace std;</p><p>const int N = 5;<br />struct offset{<br /> int x,y;<br />} d[]={{0,1},{0,-1},{-1,0},{1,0}};<br />const int d_num = sizeof(d)/sizeof(offset);<br />bool f[N][N];<br />bool maze[N][N];<br />struct node{<br /> node(int a,int b,int c=0,int d=0):x(a),y(b),prex(c),prey(d){}<br /> int x,y;<br /> int prex,prey;<br />};<br />bool isOK(int x, int y){<br /> return (!f[x][y] && !maze[x][y] && x>=0 && x<=4 && y>=0 && y<=4);<br />}<br />/*find the shortest path from start point(0,0) to finish point(N-1,N-1)*/<br />int main()<br />{<br /> queue<node*> q;<br /> vector<node*> q1;<br /> int sx,sy,fx,fy;<br /> sx=sy=0;//set the start point<br /> fx=fy=N-1;//set the finish point</p><p> q.push(new node(sx,sy,-1,-1));<br /> memset(f,false,sizeof(f));<br /> f[sx][sy]=true;<br /> for(int i=0;i<N;i++)<br /> for(int j=0;j<N;j++)<br /> cin >> maze[i][j];<br /> while(!q.empty()){<br /> int x,y;<br /> x = q.front()->x;<br /> y = q.front()->y;<br /> q1.push_back(q.front());//record the path<br /> if(x==fx && y==fy)break;//may be sx==fx && sy==fy<br /> q.pop();<br /> for(int i=0;i<d_num;i++){<br /> int new_x=x+d[i].x;<br /> int new_y=y+d[i].y;<br /> if(isOK(new_x, new_y)){<br /> q.push(new node(new_x, new_y,x,y));<br /> f[new_x][new_y]=true;<br /> }<br /> }<br /> }<br /> //print the path<br /> if(!q1.empty() && q1[q1.size()-1]->x==fx && q1[q1.size()-1]->y==fy){<br /> stack<node*> s;<br /> int curX = fx, curY = fy;<br /> while(!(curX==sx && curY==sy)){<br /> s.push(new node(curX,curY));<br /> for(vector<node*>::iterator it=q1.begin();it!=q1.end();it++){<br /> if((*it)->x==curX && (*it)->y==curY){<br /> curX = (*it)->prex;<br /> curY = (*it)->prey;<br /> break;<br /> }<br /> }<br /> }<br /> s.push(new node(curX,curY));<br /> while(!s.empty()){<br /> cout << "(" << s.top()->x << ", " << s.top()->y <<")" << endl;<br /> delete s.top();<br /> s.pop();<br /> }<br /> }else{<br /> cout << "No Way!" << endl;<br /> }<br /> return 0;<br />}<br />

聯繫我們

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