注意:
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'))