为什么在 BFS 末尾打印 1?
Why is a 1 being printed at the end of BFS?
下面是无向图上的简单广度优先搜索。
问题是找出源节点和目标节点之间是否存在路径。代码有效,但我不明白为什么要在最后打印 1
。
节目:
#include <iostream>
#include <unordered_map>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
bool BFS(unordered_map<int, vector<int>> &umap, int source, int dest) {
queue<int> q;
vector<int> v;
q.push(source);
while (!q.empty()) {
int front = q.front();
if (find(v.begin(), v.end(), front) == v.end()) {//element is not visited yet
cout << static_cast<char>(front) << " -> ";
if (front == dest)
return true;
v.push_back(front);
for (auto &i: umap[front])
q.push(i);
}
q.pop();
}
return false;
}
int main() {
unordered_map<int, vector<int>> umap;
umap['i'] = {'j', 'k'};
umap['j'] = {'i'};
umap['k'] = {'i', 'm', 'p'};
umap['m'] = {'k'};
umap['p'] = {'k'};
umap['o'] = {'n'};
umap['n'] = {'o'};
cout << endl
<< "------------BFS------------"
<< endl;
cout << BFS(umap, 'j', 'm');
}
输出:
------------BFS------------
j -> i -> k -> m -> 1
Process finished with exit code 0
关于这个问题的第一条评论总结了这一点——我忽略了我正在打印 bool
(cout << BFS(umap, 'j', 'm');
) 的事实,所以在这种情况下预期会出现 1
找到路径(值为true
)。
下面是无向图上的简单广度优先搜索。
问题是找出源节点和目标节点之间是否存在路径。代码有效,但我不明白为什么要在最后打印 1
。
节目:
#include <iostream>
#include <unordered_map>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
bool BFS(unordered_map<int, vector<int>> &umap, int source, int dest) {
queue<int> q;
vector<int> v;
q.push(source);
while (!q.empty()) {
int front = q.front();
if (find(v.begin(), v.end(), front) == v.end()) {//element is not visited yet
cout << static_cast<char>(front) << " -> ";
if (front == dest)
return true;
v.push_back(front);
for (auto &i: umap[front])
q.push(i);
}
q.pop();
}
return false;
}
int main() {
unordered_map<int, vector<int>> umap;
umap['i'] = {'j', 'k'};
umap['j'] = {'i'};
umap['k'] = {'i', 'm', 'p'};
umap['m'] = {'k'};
umap['p'] = {'k'};
umap['o'] = {'n'};
umap['n'] = {'o'};
cout << endl
<< "------------BFS------------"
<< endl;
cout << BFS(umap, 'j', 'm');
}
输出:
------------BFS------------
j -> i -> k -> m -> 1
Process finished with exit code 0
关于这个问题的第一条评论总结了这一点——我忽略了我正在打印 bool
(cout << BFS(umap, 'j', 'm');
) 的事实,所以在这种情况下预期会出现 1
找到路径(值为true
)。