【发布时间】:2020-04-18 13:34:47
【问题描述】:
我正在实现 BFS 算法。我在 IDE 中编写了这段代码。
SYSTEM:
视窗 10
开发 c++
bfs() 函数可能有错误。我发布所有代码只是因为参考。
我的 C++ 代码:
#include<bits/stdc++.h>
using namespace std;
class Graph{
int v; // number of vertices
vector<int>*adj;
public:
/**
* Constructor to initialize the graph.
* @param v an integer: number of nodes in the graph
*/
Graph(int V){
this->v=V;
this->adj=new vector<int>[V];
}
/**
* This function add a new edge to the graph.
* @param u an integer: representing a node in the graph.
* @param v an integer: representing a node in the graph.
* @param biDir a bool: true denotes bidirectional edge, unidirectional otherwise.
*/
void addEdge(int u,int v,bool biDir=false){
adj[u].push_back(v);
if(biDir)
adj[v].push_back(u);
}
/**
* This function traverse the given graph using BFS traversal technique.
* @param src a node: function starts traversing from this node.
*/
void bfs(int src){
// create a array of boolean to keep track of visited nodes.
vector<bool>visited(this->v,false);
// visited[0]=true;
// make a queue and insert src into it
queue<int>q;
q.push(src); // insert src into queue
// mark first node as visited
visited[src]=true;
while(!q.empty()){
int node=q.front();
// visit
cout<<node<<" ";
// remove this node from queue
q.pop();
// visit every node adjacent to node 'node'
// if that node not visited then visit and enque it.
for(int adjNode:adj[node]){
if(!visited[adjNode]){
visited[adjNode]=true;
q.push(adjNode);
}
}
}
}
void print(){
// for every vertex
for(int i=1;i<this->v;i++){
// every connected edge from vertex
cout<<i<<"-> ";
for(int node:adj[i]){
cout<<node<<" ";
}
cout<<endl;
}
}
};
int main(){
Graph g(5+1);
g.addEdge(1,2);
g.addEdge(1,4);
g.addEdge(4,6);
g.addEdge(3,6);
g.addEdge(2,5);
g.addEdge(5,2);
g.addEdge(6,3);
g.addEdge(6,4);
g.print();
cout<<endl;cout<<endl;cout<<endl;cout<<endl;
g.bfs(1);
return 0;
}
虽然这个程序编译得很好。但是在运行时,只有 print() 函数会执行。函数 bfs() 不执行。
它产生以下 OUTPUT: 由 print() 函数生成。
1-> 2 4
2-> 5
3-> 6
4-> 6
5-> 2
当我在 bfs() 中更改此代码时
vector<bool>visited(this->v,false);
致此
bool visited[this->v];
for(int i=0;i<this->v;i++)
visited[i]=false;
此代码也不执行 bfs()。
【问题讨论】:
-
在我的情况下,当我重新安装编译器时,它对我有用。 -- 什么?我希望可以使用向下投票的 cmets。很可能,您的程序有未定义的行为,可能是由于未初始化的变量或越界访问。 @OP -- 请不要重新安装你的编译器。
-
@rahulkumar -- 你错了。仅仅因为程序编译正常,not 是否意味着它在逻辑上是正确的或没有错误。编译正常意味着程序没有语法错误。此外,
bits标头不是标准的——您应该包含正确的 C++ 标头。 -
我无法找到为什么我的程序会简单地终止(崩溃)的错误?您需要访问调试器。使用它来追踪崩溃发生的位置。
-
第二个调试器建议。如果您不知道如何使用调试器,请学习如何使用。不使用调试器就像开车没有镜子一样。我看到的一个具体问题是您创建了一个包含 6 个节点(有效索引 0 -> 5)的图,然后尝试访问索引为 6 的节点。不确定这是否是您唯一的问题,但这是第一个大问题。创建图表时使用“5 + 1”令人担忧。如果您想要 5 个节点,请输入 5。如果您想要 6 个节点,请输入 6。这让我觉得您正在尝试通过逐一显示和引入逐一错误来变得聪明。
-
是的,一个问题是您访问的向量越界。
标签: c++ breadth-first-search dev-c++