【BFS終於變水】HDU 1242——Rescue

來源:互聯網
上載者:User

來源:點擊開啟連結

終於把BFS看水了,包括路徑最佳化和奇偶剪枝。一年了也就看明白了這點東西,so sad。。。。

#include <iostream>#include <cstring>#include <algorithm>#include <queue>using namespace std;int visited[205][205];char mat[205][205];int n,m;int dir[4][2]={-1,0,1,0,0,1,0,-1};class node{public:int x;int y;int step;};bool judge(int x,int y){if(x>=0 && x<n && y>=0 && y<m && visited[x][y]==0 && mat[x][y]!='#')return 1;elsereturn 0;}int bfs(node st,node ed){memset(visited,0,sizeof(visited));queue<node> q;node first,next;first.x=st.x;first.y=st.y;first.step=0;visited[first.x][first.y]=1;q.push(first);while(!q.empty()){first=q.front();q.pop();for(int i=0;i<4;i++){next.x=first.x+dir[i][0];next.y=first.y+dir[i][1];next.step=first.step;if(next.x==ed.x && next.y==ed.y)return next.step+1;if(judge(next.x,next.y) && mat[next.x][next.y]=='.'){next.step+=1;visited[next.x][next.y]=1;q.push(next);}if(judge(next.x,next.y) && mat[next.x][next.y]=='x'){next.step+=2;visited[next.x][next.y]=1;q.push(next);}}}return -1;}int main(){while(cin>>n>>m){node s1,e1;for(int i=0;i<n;i++){for(int j=0;j<m;j++){cin>>mat[i][j];if(mat[i][j]=='a'){s1.x=i;s1.y=j;}if(mat[i][j]=='r'){e1.x=i;e1.y=j;}}}int res=bfs(s1,e1);if(res!=-1){cout<<res<<endl;}else{cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;}}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.