POJ

来源:互联网 发布:word电脑软件 编辑:程序博客网 时间:2024/05/18 15:26
定义一个二维数组:

int maze[5][5] = {

0, 1, 0, 0, 0,

0, 1, 0, 1, 0,

0, 0, 0, 0, 0,

0, 1, 1, 1, 0,

0, 0, 0, 1, 0,

};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output

左上角到右下角的最短路径,格式如样例所示。


题意:中文题0.0

思路:就是普通的bfs,打印路径的话就加一个pre数组储存前一个


代码:

#include <cstdio>#include <cmath>#include <iostream>#include <cstring>#include <algorithm>#include <queue>#include <stack>#include <vector>#include <map>#include <numeric>#include <set>#include <string>#include <cctype>#include <sstream>#define INF 0x3f3f3f3f#define lson l, m, rt<<1#define rson m+1, r, rt<<1|1typedef long long LL;using namespace std;const int maxn = 20 + 5;const int mod = 1e8 + 7;int mp[5][5];bool vis[5][5];int to[4][2]={1,0,-1,0,0,1,0,-1};struct node{    int x,y;    int step;}now,next;node pre[maxn][maxn];void bfs(){    queue<node>q;    now.x=0;    now.y=0;    now.step=0;    q.push(now);    vis[0][0]=1;    while (!q.empty()){        node n=q.front();        q.pop();        if (n.x==4&&n.y==4) return;        for (int i=0;i<4;i++){            next.x=n.x+to[i][0];            next.y=n.y+to[i][1];            next.step=n.step+1;            if (next.x<0||next.y<0||next.x>=5||next.y>=5) continue;            if (mp[next.x][next.y]==1) continue;            if (vis[next.x][next.y]) continue;            pre[next.x][next.y].x=n.x;            pre[next.x][next.y].y=n.y;            vis[next.x][next.y]=1;            q.push(next);        }    }}void print(int x,int y){    if (x==0&&y==0){        printf ("(%d, %d)\n",0,0);        return;    }    print(pre[x][y].x,pre[x][y].y);    printf ("(%d, %d)\n",x,y);}int main() {    //freopen ("in.txt", "r", stdin);    for (int i=0;i<5;i++){        for (int j=0;j<5;j++){            scanf ("%d",&mp[i][j]);        }    }    bfs();    print(4,4);    return 0;}