采用map,queue结合的方式执行广度优先算法,并导出最短路径

采用map,queue结合的方式执行广度优先算法,并导出最短路径

#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <stack>
using namespace std;


struct Node
{
    bool State[4] = {false,false,false,false};
};

bool findMazePathByBFS(vector<vector<int>>& maze, vector<pair<int,int>>& bestPath)
{
    int Row = maze.size();
    if(Row < 2)
    {
        return false;
    }
    int Column = maze[0].size();
    if(Column < 2)
    {
        return false;
    }
    if(maze[0][0] == 1)
    {
        return false;
    }
    map<pair<int,int>,Node> mazeMap;
    for(int i = 0;i<Row;i++)
    {
        for(int j=0;j<Column;j++)
        {
            if(maze[i][j] == 1) //标记每个可通过点右下左上的状态,为1不可通过,继续循环
            {
                continue;
            }
            pair<int,int> tempPair(i,j);
            Node tempNode;
            if(j+1<Column&&maze[i][j+1] == 0) //右
            {
                tempNode.State[0] = true;
            }
            if(i+1<Row&&maze[i+1][j] == 0) //下
            {
                tempNode.State[1] = true;
            }
            if(j-1>=0&&maze[i][j-1] == 0) //左
            {
                tempNode.State[2] = true;
            }
            if(i-1>=0&&maze[i-1][j] == 0) //上
            {
                tempNode.State[3] = true;
            }
            mazeMap[tempPair] = tempNode; //存放在map中,通过坐标可以访问对应的状态
        }
    }
    queue<pair<int,int>> PointQueue; //用来执行广度优先搜索的队列
    PointQueue.push(make_pair(0,0));//存入起点坐标
    map<pair<int,int>,pair<int,int>> ResultMap; //key值为对应每点坐标,value值代表这个点的上一个坐标是啥
    bool isEnabled = false;
    while(PointQueue.size() != 0)
    {
        pair<int,int> Tmp = PointQueue.front(); //获取队首坐标
        PointQueue.pop();//出队列
        if(mazeMap[Tmp].State[0]) //右可通行
        {
            mazeMap[Tmp].State[0] = false;
            pair<int,int> RightNode = make_pair(Tmp.first,Tmp.second+1);
            mazeMap[RightNode].State[2] = false; //在右节点中将右节点的左节点,也就是本节点的状态设置为不可通行
            ResultMap[RightNode] = Tmp;
            if(RightNode.first+1 == Row && RightNode.second+1 == Column)
            {
                isEnabled = true;
                break;
            }
            PointQueue.push(RightNode);
        }
        if(mazeMap[Tmp].State[1])//下可通行
        {
            mazeMap[Tmp].State[1] = false;
            pair<int,int> DownNode = make_pair(Tmp.first+1,Tmp.second);
            mazeMap[DownNode].State[3] = false;
            ResultMap[DownNode] = Tmp;
            if(DownNode.first+1 == Row && DownNode.second+1 == Column)
            {
                isEnabled = true;
                break;
            }
            PointQueue.push(DownNode);
        }
        if(mazeMap[Tmp].State[2]) //左可通行
        {
            mazeMap[Tmp].State[2] = false;
            pair<int,int> LeftNode = make_pair(Tmp.first,Tmp.second-1);
            mazeMap[LeftNode].State[0] = false;
            ResultMap[LeftNode] = Tmp;
            PointQueue.push(LeftNode);
        }
        if(mazeMap[Tmp].State[3]) //上可通行
        {
            mazeMap[Tmp].State[3] = false;
            pair<int,int> UpNode = make_pair(Tmp.first-1,Tmp.second);
            mazeMap[UpNode].State[1] = false;
            ResultMap[UpNode] = Tmp;
            PointQueue.push(UpNode);
        }
    }
    cout<<"resultMap size:"<< ResultMap.size()<< endl;
    if(isEnabled)
    {
        stack<pair<int,int>> sq;
        pair<int,int> TargetPair = make_pair(Row-1,Column-1);
        sq.push(TargetPair);
        while(!(TargetPair.first == 0 && TargetPair.second == 0))
        {
            pair<int,int> temp = ResultMap[TargetPair];
            sq.push(temp);
            TargetPair.first = temp.first;
            TargetPair.second = temp.second;
        }
        bestPath.clear();
        while(!sq.empty())
        {
            bestPath.push_back(sq.top());
            sq.pop();
        }
        return true;
    }
    return false;
}
int main()
{
    int a[9][7]={{0,0,0,0,0,0,0},
                 {1,1,1,0,1,1,0},
                 {1,1,1,0,1,1,0},
                 {1,1,0,0,1,0,0},
                 {1,0,0,0,0,1,0},
                 {1,0,1,1,1,0,0},
                 {1,0,1,1,0,0,0},
                 {1,0,1,1,0,1,1},
                 {1,1,1,1,0,0,0}};
    vector<vector<int>> maze(9,vector<int>(7));
    for(int i=0;i<9;i++)
    {
        for(int j=0;j<7;j++)
        {
            maze[i][j] = a[i][j];
        }
    }
    vector<pair<int,int>> bestPath;
    cout << findMazePathByBFS(maze,bestPath) <<endl;
    for(auto it : bestPath)
    {
        cout << it.first<<","<<it.second<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,针对你的问题,我可以给出以下的 Python 代码实现: ``` from collections import deque # 定义有向图的邻接表表示 graph = { 'A': {'B': 1, 'C': 4}, 'B': {'D': 2}, 'C': {'D': 1}, 'D': {'E': 3}, 'E': {} } # 定义广度优先算法最短路径 def bfs_shortest_path(graph, start, end): queue = deque([(start, [start])]) # 使用双向队列,初始化为起点 visited = set() # 记录已访问的节点 while queue: node, path = queue.popleft() # 取出队列中的节点和路径 if node not in visited: # 如果节点没有被访问过 visited.add(node) # 标记为已访问 if node == end: # 如果找到了终点 return path # 返回路径 for neighbor, weight in graph[node].items(): # 遍历邻居节点 if neighbor not in visited: # 如果邻居节点没有被访问过 queue.append((neighbor, path + [neighbor])) # 将邻居节点加入队列,并记录路径 return None # 如果没有找到路径,返回 None # 测试代码 start = 'A' end = 'E' shortest_path = bfs_shortest_path(graph, start, end) if shortest_path: print(f"The shortest path from {start} to {end} is: {' -> '.join(shortest_path)}") else: print(f"There is no path from {start} to {end}") ``` 在这个例子中,我们定义了一个有向图的邻接表表示,使用 `deque` 实现双向队列,并采用广度优先搜索算法来搜索最短路径。最后,我们利用测试代码对算法进行测试,输出最短路径结果。 希望这个例子能够帮助你理解如何利用广度优先算法找出最短路径

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值