[英]What's wrong with this implementation of Breadth First Search?
Here is my whole program:这是我的整个程序:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
void addEdge(vector<int> adjList[], int u, int v) {
adjList[u].push_back(v);
adjList[v].push_back(u);
}
void bfs(int s, vector<int> adjList[], vector<bool> visited, int V) {
queue<int> q;
q.push(s);
visited[s] = true;
while (!q.empty()) {
int cur = q.front();
q.pop();
cout << cur << " ";
for (int i = 0; i < adjList[cur].size(); i++) {
if (!visited[i]) {
q.push(adjList[cur][i]);
visited[i] = true;
}
}
}
}
int main() {
int V = 4;
vector<int> adj[4];
vector<bool> visited;
visited.assign(V, false);
addEdge(adj, 0, 1);
addEdge(adj, 2, 3);
addEdge(adj, 3, 4);
bfs(0, adj, visited, V);
return 0;
}
I want to perform Breadth First Search (BFS) and print out nodes as they are discovered.我想执行广度优先搜索 (BFS) 并在发现节点时打印出它们。 For some reason this isn't printing anything.
出于某种原因,这不会打印任何内容。 What have I done wrong?
我做错了什么?
You have out-of-bounds access to adj
.您可以越界访问
adj
。 It has size 4
, but in addEdge(adj, 3, 4);
它的大小为
4
,但在addEdge(adj, 3, 4);
you're writing into the 4-th element (5-th in one-based indexing).您正在写入第 4 个元素(基于一个的索引中的第 5 个)。
The condition if (!visited[i])
doesn't make sense.条件
if (!visited[i])
没有意义。 i
should be replaced with the next node index, ie adjList[cur][i]
. i
应该替换为下一个节点索引,即adjList[cur][i]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.