【刷题算法】广度优先遍历BFS的最短路算法

本文介绍了宽度优先搜索(BFS)算法的实现方法,并提供了C++和Python两种语言的示例代码。通过这些代码,读者可以了解到如何使用BFS算法寻找图中两点之间的最短路径。

注意:
BFS的最短路只适合用于每条带权边的权重相同。如果每条边的权重不同,则BFS将不适用。

这里不再解释BFS的基本概念,仅仅贴出两种语言(C++, python)的实现代码

C++ 实现

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


vector<vector<int> > BFS(multimap<int, int> mcc, int start, int end) {
    vector<vector<int> > allpath;
    vector<int> path;
    queue<vector<int>> q;

    path.push_back(start);
    q.push(path);
    while (!q.empty()) {
        vector<int> path_tmp = q.front();
        int node = path_tmp[path_tmp.size() - 1];
        if (node == end) {
            allpath.push_back(path_tmp);
            // break;  //加上break 返回最短路; 否则返回所有路径
        }
        for (auto it = mcc.lower_bound(node); it != mcc.upper_bound(node); it++) {
            vector<int> new_path = path_tmp;
            new_path.push_back(it->second);
            q.push(new_path);
        }
        q.pop();
    }
    return allpath;
}


int main() {
    //graph = {
    //  '1': ['2', '3', '4'],
    //  '2' : ['5', '11'],
    //  '5' : ['9', '10'],
    //  '4' : ['7', '8'],
    //  '7' : ['11', '12']
    //}

    multimap <int,int> mcc;
    mcc.insert(make_pair(1, 2));
    mcc.insert(make_pair(1, 3));
    mcc.insert(make_pair(1, 4));
    mcc.insert(make_pair(2, 5));
    mcc.insert(make_pair(2, 11));
    mcc.insert(make_pair(5, 9));
    mcc.insert(make_pair(5, 10));
    mcc.insert(make_pair(4, 7));
    mcc.insert(make_pair(4, 8));
    mcc.insert(make_pair(7, 11));
    mcc.insert(make_pair(7, 12));

    vector<vector<int> > vvi = BFS(mcc,1,11);
    for (int i = 0; i < vvi.size(); i++) {
        for (int j = 0; j < vvi[i].size(); j++)
            cout << vvi[i][j] << " ";
        cout << endl;
    }

    system("pause");
}

python 实现

# graph is in adjacent list representation  
graph = {  
        '1': ['2', '3', '4'],  
        '2': ['5', '6'],  
        '5': ['9', '10'],  
        '4': ['7', '8'],  
        '7': ['11', '12']  
        }  

def bfs(graph, start, end):  
    # maintain a queue of paths  
    queue = []  
    # push the first path into the queue  
    queue.append([start])  
    while queue:  
        # get the first path from the queue  
        path = queue.pop(0)  
        # get the last node from the path  
        node = path[-1]  
        # path found  
        if node == end:  
            return path  
        # enumerate all adjacent nodes, construct a new path and push it into the queue  
        for adjacent in graph.get(node, []):  
            new_path = list(path)  
            new_path.append(adjacent)  
            queue.append(new_path)  


print(bfs(graph, '1', '11'))  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值