查找路径的有向图邻接矩阵
Directed Graph Adjacency Matrix Finding the Path
我正在尝试使用 BFS 方法搜索我的图形,然后确定我的两个节点之间是否存在路径。 我理解它并可以使用链表实现它,但我只是无法用矩阵来掌握它。
我相信我在循环部分出错了,我觉得我在迭代错误的事情,或者可能比较了错误的值。 感谢您的任何帮助。
这是我的代码:
#include <iostream>
#include <queue>
#include <string.h>
#include <stack>
#include <list>
using namespace std;
class Graph{
private:
int total_routes;
int total_stations;
public:
int AdjMatrix[100][100];
Graph(int routes, int stations);
void addRoute(int from, int to, int weight);
void printGraph();
bool isRoute(int from, int to);
};
Graph::Graph(int routes, int stations)
{
for(int i = 0; i < stations; i++){
for(int j=0; j < stations; j++){
AdjMatrix[i][j]=0;
}
}
total_routes = routes;
total_stations = stations;
}
void Graph::printGraph(){
cout << "n" << endl;
for(int i = 0; i < total_stations; i ++){
for(int j = 0; j < total_stations; j++){
cout << " " << AdjMatrix[i][j];
}
cout << endl;
}
}
void Graph::addRoute(int from, int to, int weight){
AdjMatrix[from][to] = weight;
}
bool Graph::isRoute(int from, int to){
bool route = false;
bool visited[total_stations] = {false};
queue<int> verticies;
if (from == to){
cout << "Going into if its the same node statement" << endl;
return true;
}
visited[from] = true;
verticies.push(from);
cout << "Testing if there is a route from " << from << " To " << to << endl;
while(!verticies.empty() && route == false ){
int current;
current = verticies.front();
verticies.pop();
cout << "Going into for Loop, with a current value of " << current << endl;
for ( int i = AdjMatrix[current][0]; i < total_stations ; i++ ){
if (i == to ){
route = true;
break;
}
if ( visited[i] == false){
visited[i] = true;
verticies.push(i);
}
}
}
return route;
}
int main() {
Graph newGraph(2,10); //10 stations(Nodes), 2 routes
newGraph.addRoute(0,1,10); //Route from 1 to 2, with a weight of 10.
newGraph.addRoute(2,9,1); //Route of 2 to 9, with a weight of 1.
newGraph.printGraph();
bool answer = newGraph.isRoute(3,9); //Should say no route...
if (answer){
cout << "There is a route!" << endl;
}
else{
cout << "There is no route!" << endl;
}
return 0;
}
最好使用
NULL 初始化 AdjMatrix[i][j]
然后你可以做
for ( int i = 0; i < total_stations ; i++ ){
if (AdjMatrix[current][i]!=NULL)
{
if (i == to ){
route = true;
break;
}
if ( visited[i] == false){
visited[i] = true;
verticies.push(i);
}
}
你应该以这种方式迭代
for ( int i = 0; i < total_stations ; i++ )
并检查是否
visited[i] == false && AdjMatrix[current][i] != 0
将新顶点推送到队列中。
相关文章:
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- C++创建指向有向图中节点的指针数组
- 如何仅在 2 个节点之间获取最短路径,给定邻接列表有向图?
- 有向图 - 如何计算图中彼此顶点可到达的顶点数?
- C++计算有向图中的最短路径
- 使用非递归 DFS 检测有向图中的周期
- 如何将这些节点连接为有向图
- 如何使用广度优先搜索确定是否可以在有向图中到达顶点
- 在有向图中精确访问所有节点一次
- 在有向图中查找第二条最短路径
- 关于如何处理有向图的一个想法
- 找到有向图C 的最短路径
- 分析输入文件以创建有向图C++
- 在使用无序多映射实现的有向图中查找循环
- 如何找到在c++中实现的有向图的所有路径作为邻接列表
- 查找路径的有向图邻接矩阵
- 将边添加到使用链表实现的有向图(邻接列表)C++
- 使用c++向量的有向图的邻接列表表示
- 将文本文件解析为C++有向图或邻接列表
- 从c++文本文件中读取有向图的邻接表