035_迷宫最短路径

来源:互联网 发布:网络招生宣传方案 编辑:程序博客网 时间:2024/04/29 07:51

经典的BFS问题, 貌似amazon有道题和这个挺像的~~

参见《挑战程序竞赛》第二版34页。 用队列实现比较方便。

依旧XCODE 蛋疼中。废话不多说了,直接po c++代码。

////  035_bfs.cpp//  changlle////  Created by user on 12/24/15.//  Copyright (c) 2015 user. All rights reserved.//#include <iostream>#include <queue>using namespace std;const int INF=100000000;typedef pair<int, int> P;char maze[5][5]={    {'#','s','#','.','#',},    {'#','.','.','.','#',},    {'#','.','#','.','#',},    {'#','.','#','.','#',},    {'#','.','#','g','#',},};int N=5,M=5;int sx=0, sy=1;int gx=4,gy=3;int d[5][5];int dx[4]={1,0,-1,0}, dy[4]={0,-1,0,1};int bfs();int main (){    int dis=bfs();        cout<<dis<<endl;        for (int i=0;i<N;i++){        for (int j=0;j<M;j++){            cout<< d[i][j]<<"    ";        }        cout<<endl;    }        return 0;}int bfs(){        for (int i=0;i<N;i++)        for (int j=0;j<M;j++)            d[i][j]=INF;    d[sx][sy]=0;        queue<P> que;        que.push(P(sx,sy));        while (que.size()) {                        P now=que.front();        que.pop();                            for (int i=0;i<4;i++){                                int tempx=now.first+dx[i];                int tempy=now.second+dy[i];                                if (now.first==gx && now.second==gy)  break;                                if (0<=tempx && tempx <=4 && 0<= tempy && tempy<=4 && maze[tempx][tempy]!='#' && d[tempx][tempy]==INF)                {                    d[tempx][tempy]=d[now.first][now.second]+1;                    que.push(P(tempx,tempy));                                    }                                                            }            }            return d[gx][gy];    }

1 0
原创粉丝点击