POJ 3984

题意

定义一个二维数组表示迷宫, 0为通道, 1为墙壁
左上(0,0)为迷宫入口, 右下角(4,4)为出口
求最短路的坐标( 输入保证有且只有一个最优解 )

思路

BFS
二维数组maze[][]存的是迷宫图
二维数组vis[][]用于标记该位置是否曾经走过(如果走过, 那么第一次踩到该位置的走法是最短路)
数组pre[]存放的是改点前驱

AC代码

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

const int maxn = 100 + 10;
int maze[6][6], vis[6][6], pre[maxn];
int turn[4][2] = {1,0,-1,0,0,1,0,-1};    //搜索的四个方向

struct point{
    int x, y;
}que[maxn];

void print( int a ){
    int t = pre[a];
    if( t != 0 )
        print(t);
    else
        printf("(0, 0)
");
    printf("(%d, %d)
",que[a].x, que[a].y);
}

bool CanGo( int x, int y )
{
    if( x < 5 && y < 5 && x >= 0 && y >= 0 && maze[x][y] == 0 )
        return true;
    return false;
}

void BFS(){
    memset(vis,0,sizeof(vis));
    int head = 0, tail = 1, a, b, xx, yy;
    que[0].x = 0;
    que[0].y = 0;
    pre[0] = -1;
    while( head < tail )    //如果队列不为空
    {
        a = que[head].x;
        b = que[head].y;
        if( a == 4 && b == 4 ){
            print(head);
            return;
        }
        for( int i = 0; i < 4; i++ ){ //搜索四个方向
            xx = a + turn[i][0];
            yy = b + turn[i][1];
            if( !vis[xx][yy] && CanGo(xx,yy) )
            {  //符合条件进队
                que[tail].x = xx;
                que[tail].y = yy;
                pre[tail] = head;
                tail++;
                vis[xx][yy] = 1;
            }
        }
        head++;  //出队
    }
    return;
}

int main()
{
    for( int i = 0; i < 5; i++ )
        for( int j = 0; j < 5; j++ )
            scanf("%d",&maze[i][j]);
    BFS();
    return 0;
}
原文地址:https://www.cnblogs.com/JinxiSui/p/9740600.html