我正在尝试用C ++实现图形和广度优先遍历算法。 这是我关注的代码
#include<iostream>
#include <list>
using namespace std;
class Graph
{
int V; // No. of vertices
list<int> *adj; // Pointer to an array containing adjacency lists
public:
Graph(int V); // Constructor
void addEdge(int v, int w); // function to add an edge to graph
bool isReachable(int s, int d); // returns true if there is a path from s to d
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
// A BFS based function to check whether d is reachable from s.
bool Graph::isReachable(int s, int d)
{
// Base case
if (s == d)
return true;
// Mark all the vertices as not visited
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;
// Create a queue for BFS
list<int> queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
// it will be used to get all adjacent vertices of a vertex
list<int>::iterator i;
while (!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
queue.pop_front();
// Get all adjacent vertices of the dequeued vertex s
// If a adjacent has not been visited, then mark it visited
// and enqueue it
for (i = adj[s].begin(); i != adj[s].end(); ++i)
{
// If this adjacent node is the destination node, then return true
if (*i == d)
return true;
// Else, continue to do BFS
if (!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
return false;
}
// Driver program to test methods of graph class
int main()
{
// Create a graph given in the above diagram
Graph g(23);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.addEdge(4, 5);
g.addEdge(5, 6);
g.addEdge(6, 7);
g.addEdge(7, 8);
g.addEdge(8, 9);
g.addEdge(9, 10);
g.addEdge(10, 11);
g.addEdge(11, 12);
g.addEdge(12, 13);
g.addEdge(13, 14);
g.addEdge(14, 15);
g.addEdge(15, 16);
g.addEdge(8, 17);
g.addEdge(17, 18);
g.addEdge(18, 19);
g.addEdge(19, 20);
g.addEdge(20, 21);
g.addEdge(21, 22);
g.addEdge(22, 23);
g.addEdge(23, 16);
int u = 1, v = 3;
if(g.isReachable(u, v))
cout<< "\n There is a path from " << u << " to " << v;
else
cout<< "\n There is no path from " << u << " to " << v;
u = 3, v = 1;
if(g.isReachable(u, v))
cout<< "\n There is a path from " << u << " to " << v;
else
cout<< "\n There is no path from " << u << " to " << v;
return 0;
}
在主方法中,如果我包括添加到26,则假设它在#4; 0x4A43BC7中的未处理异常在Implementation4.exe中:0xC0000005:访问冲突读取位置0xABABABAF。&#34;异常。
无法弄清楚我在这里缺少什么。任何人都可以帮我解决这个问题。
答案 0 :(得分:0)
C ++中的索引是基于零的,而不是基于索引的。当您呼叫addGraph
时,您使用索引1到23调用它。最后一次调用addGraph
会导致它尝试将值添加到第24个 list
在只有 23 列表的数组中。要修改此更改,调用addGraph
将从0
开始并在22
结束,或者使用24个列表的数组对其进行初始化。
另外,我建议您使用裸列表列表切换到使用std::vector<list>
。这将解决内存泄漏,因为您没有删除adj
的析构函数。