BFS(最短路径)—— 迷宫问题

题目:http://www.fjutacm.com/Contest.jsp?cid=862#P2

代码:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<queue>
using namespace std;
typedef struct Node
{
    int x, y, id, from;
    //  id 是给每一个如果队列的结构体标号
    //  from 是该点所连点 所代表的结构体编号
}st; 
int map[5][5], dx[4] = { -1,0,1,0 }, dy[4] = { 0,1,0,-1 }, c = 0;
queue<st>q;
st way[50]; 
void outs(st now)
{
    if (now.from == -1)
        printf("(0, 0)
");
    else
    {
        outs(way[now.from]);;
        printf("(%d, %d)
", now.x, now.y);
    }
}
void bfs()
{
    st a = { 0,0,0,-1 };
    way[c++] = a;
    q.push(a);
    while (q.size())
    {
        st vertex = q.front();
        int pre = vertex.id;
        q.pop();
        if (vertex.x == 4 && vertex.y == 4)
        {
            outs(way[c-1]);
            return;
        }
        map[vertex.x][vertex.y] = 1;
        for (int i = 0; i < 4; i++)
        {
            st next;
            next.x = vertex.x + dx[i], next.y = vertex.y + dy[i];
            next.from = pre, next.id = c;
            if (next.x >= 0 && next.x < 5 && next.y >= 0 && next.y < 5&&map[next.x][next.y]==0)
            {
                q.push(next);
                way[c++] = next;    
            }
        }
    }
    return;
}
int main(void)
{
    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 5; j++)
        {
            scanf("%d", &map[i][j]);
        }
    }

    bfs();

    system("pause");
    return 0;
}

之前完全没想到还有这种操作,学了链式前向星才想出来。

 一,

构造一个结构体数组,一个结构体 储存 一个点的信息,

所以

类比 边集 我愿此 结构体数组 称之为  点集

二,

在 结构体 里面设两个变量,id  和 from

  id:  是给每一个 点 的的结构体标号
  from:  是该点所连的前一个点 所代表的结构体编号

如图:假设要从 A- > E

入队 顺序是:A B C D E F

则他们的 id 为:0 1 2  3 4 5    from 为: -1 0 0 1 2 3

 这样我们根据 from 就可以找到前一个的 id 了

三,

这样子做还是有缺点的:

比如 D 点, 从 B -> D 和从 E -> D,它的 from 就不一样了,即旧的路径会被新的路径覆盖。

但在这里 我们只要 最先找到的那条路径 就可以了,这也就不影响了。

如果 路是重复走到话(即绕了一圈,如图中:走 ABDECBDF),这样子也是无法记录的,

因为它绕不出来。但在最短路径里是不会出现走重复的路的,所以就没影响了。

========== ======== ========= ======= ====== ===== ==== === == =

夜月  唐 刘方平

更深月色半人家,北斗阑干南斗斜。

今夜偏知春气暖,虫声新透绿窗纱。


原文地址:https://www.cnblogs.com/asdfknjhu/p/12499112.html