在邻接矩阵上应用广度和深度优先搜索
Apply breadth and depth first search on an adjacency matrix?
我得到了这个邻接矩阵,我必须从一个文本文件中读取,并应该返回读取它的宽度优先和深度优先的结果。
我知道宽度优先使用FIFO队列,深度优先使用LIFO堆栈。我能够得到这些搜索时,我有图表,手动。我只是不确定如何在计算机上处理这个问题,并在c++上使用矩阵。
如果你能指导我如何解决这个问题,我会很感激的。我有一些问题:- 我是否将矩阵从文本文件保存到我的程序中作为常规矩阵?
- 一旦我读了文本文件来显示搜索结果,该怎么办?
ans 1:是的,最好将文本文件中的输入读入常规矩阵。
void MyGraph::csv_import()
{
int temp, i=0;
string parsed;
fstream file("input.csv");
while (getline(file, parsed, ',')) {
temp = stoi(parsed);
arr[i/10][i%10] = temp; //10 x 10 Matrix
i++;
}
}
ANS 2:选择起始节点,调用BFS显示搜索结果。例如(在我的例子中)
void MyGraph::BFS(int v)
{
memset(visited, false, sizeof(visited);
QQ.push(v); //push the starting vertex into queue
visited[v] = true; //mark the starting vertex visited
while (!QQ.empty()) //until queue is not empty
{
v = QQ.front(); //assign v the vertex on front of queue
cout << v << " "; //print the vertex to be popped
QQ.pop(); //pop the vertex on front
for (int c = 0; c< V; c++) //V is the number of nodes
{
//M[i][j] == 1, when i,j are connected
if (M[v][c] == 1 && visited[c] == false)
{ //if vertex has edge and is unvisited
QQ.push(c); //push to the queue
visited[c] = true; //mark it visited
Path[c] = p; //assign the path length
}
}
}
}
- 对
- http://www.geeksforgeeks.org/depth-first-traversal-for-a-graph/
石:注:对于无向图扫描上下三角形的矩阵就足够了。对于有向图,应该考虑整个矩阵。
Step1:维护一个布尔值数组,用于保存一个节点是否被访问。
Step2:实现队列Step3:从任意元素开始,将其推入队列并标记为已访问。目的:在循环中取消队列顶部元素的队列设置为x
对于x..的所有未访问的邻居,将它们推入队列并标记为已访问。
执行步骤4直到队列为空。
图遍历顺序是在将元素压入队列时给出的。
如果我有时间我会解释的
相关文章:
- 提升图:当我的图使用 listS 作为 VertexList 时,如何调用深度优先搜索()?
- 使用迭代深度优先搜索算法的未加权图的最短路径
- 使用后序遍历递归的深度优先搜索会产生意外输出
- 图上的深度优先搜索算法中的内存泄漏
- 为什么此函数中的运行时错误 C++ 深度优先搜索
- 通过深度优先搜索节点链接到自身进行倾倒.C++
- 矢量迭代器在尝试对图形进行深度优先搜索时导致分割错误 11
- 显示深度优先搜索图遍历C++
- 在C++中实现深度优先搜索
- 深度优先搜索过早终止
- 深度优先搜索树遍历实现在C++
- 使用邻接矩阵进行深度优先搜索
- 深度优先搜索的实施和改进
- 并行深度优先搜索C++
- 在迭代深度优先搜索(DFS)算法中确定堆栈大小
- 为什么我在这里泄漏内存(深度优先搜索)c ++
- Traversal迷宫和深度优先搜索
- 在邻接矩阵上应用广度和深度优先搜索
- 深度优先搜索树边分类
- 在c++中使用深度优先搜索查找图数据结构中所有可能的路径