【发布时间】:2018-09-05 19:45:44
【问题描述】:
我正在尝试使用邻接矩阵学习 BFS(广度优先搜索)。
我尝试了什么:
- 根本不知道 BFS 是什么,所以我学习了概念和伪代码
- 尝试查看示例
- 尝试使用指向以下数组版本的指针来实现
目标:
- 想确保我使用指向数组矩阵的指针正确地执行 BFS
邻接矩阵的图形类:
#include <iostream>
#include <queue>
using namespace std;
class Graph {
private:
bool** adjMatrix;
int numVertices;
bool* visited;
public:
//constructor
Graph(int numVertices) {
this->numVertices = numVertices;
adjMatrix = new bool*[numVertices];
for(int i = 0; i < numVertices; i++) {
adjMatrix[i] = new bool[numVertices];
for(int j = 0; j < numVertices; j++)
adjMatrix[i][j] = false;
}
visited[numVertices]; //init visited array
}
//member function
void BFS(int sp) {
//make a queue of type int
queue<int> Q;
//make bool visited array & mark all positions unvisited
for(int i = 0; i < numVertices; i++)
visited[i] = false;
//push sp into queue
Q.push(sp);
//mark sp as visited
visited[sp] = true;
//while queue isn't empty
while(!Q.empty()) {
//make temp node
int temp = Q.front();
//pop temp node
Q.pop();
//use loop & check if it has children
int rows = sizeof adjMatrix / sizeof adjMatrix[0]; //get row size
for(int i = 0; i < rows; i++) { //check neighboring nodes
if(!visited[i] && adjMatrix[sp][i] == true) {
Q.push(i); //if so push them into queue
visited[i] = true; //mark children as visited
}
}
}
}
};
【问题讨论】:
-
问题出在哪里?
-
我正在尝试找出是否有问题。我认为它可能在while循环内
-
我的意思是,问题是什么?有什么不正常吗?您是否尝试编译并运行它?
-
更重要的是,您从未问过问题。无论如何,我绝对不怀疑
sizeof adjMatrix / sizeof adjMatrix[0]是错误的。adjMatrix是一个指向指针的指针(指向bool,但现在并不真正相关),所以sizeof adjMatrix / sizeof adjMatrix[0]将是1总是。很确定numVerticies将进入这张图片,假设你的指针数组确实在所有行中都那么宽。 -
如果您不确定发生了什么,修复它的第一步是在调试器中单步调试代码。
标签: c++ data-structures queue