邻接列表中的深度优先或广度算法
Depth first or breadth algorithm in adjacency List
我最近开始了C++编程,我想知道如何实现深度优先或广度算法。我一直在尝试做这件事,但我失败得很厉害,所以如果你能用提供的例子给我看,那将非常有帮助。
#include <iostream>
#include <cstdlib>
using namespace std;
struct AdjancancyListNode
{
int destination;
struct AdjancancyListNode* next;
};
struct AdjancancyList
{
struct AdjancancyListNode *head;
};
class Graph
{
private:
int V;
struct AdjancancyList* array;
void DFSUtil(int v, bool visited[]);
public:
Graph(int V)
{
this->V = V;
array = new AdjancancyList [V];
for (int i = 0; i < V; ++i)
array[i].head = 0;
}
/*
* Adding Edge to Graph
*/
void addEdge(int s, int destination)
{
AdjancancyListNode* newNode = newAdjListNode(destination);
newNode->next = array[s].head;
array[s].head = newNode;
newNode = newAdjListNode(s);
newNode->next = array[destination].head;
array[destination].head = newNode;
}
/*
* Creating New Adjacency List Node
*/
AdjancancyListNode* newAdjListNode(int destination)
{
AdjancancyListNode* newNode = new AdjancancyListNode;
newNode->destination = destination;
newNode->next = 0;
return newNode;
}
/*
* Print the graph
*/
void printGraph()
{
int v;
for (v = 0; v < V; ++v) /* going through the edges */
{
AdjancancyListNode* pCrawl = array[v].head;
cout<<endl<<" Adjacency list of vertex |"<<v<<"|"<<endl<<" head ";
while (pCrawl)
{
cout<<"-> |"<<pCrawl->destination<<"|";
pCrawl = pCrawl->next;
}
cout<<endl;
}
}
};
int main()
{
Graph gh(9); /* declaring the graph with 5 vertexes */
gh.addEdge(0, 1);/* Adding edges */
gh.addEdge(0, 3);
gh.addEdge(1, 2);
gh.addEdge(1, 3);
gh.addEdge(2, 4);
gh.addEdge(2, 3);
gh.addEdge(4, 5);
gh.addEdge(5, 6);
gh.addEdge(5, 1);
gh.addEdge(3, 9);
gh.addEdge(8, 7);
gh.addEdge(7, 0);
gh.addEdge(9, 1);
// print the adjacency list representation of the above graph
gh.printGraph(); /* showing the graph*/
return 0;
}
你可以用这样的向量实现邻接列表,这比使用指针容易得多。检查代码,也更容易理解它的工作原理。
#include <bits/stdc++.h>
using namespace std;
vector<int> edges[5];
bool visited[5];
void dfs(int x)
{
visited[x] = true;
for(int i=0; i < edges[x].size(); i++)
if(!visited[edges[x][i]])
dfs(edges[x][i]);
}
int main()
{
for(int i=0; i < 5; i++)
visited[i] = false;
vector<pair<int, int> > inputEdges{{0, 1}, {1, 2}, {0, 3}, {3, 4}, {1, 4}};
for(int i=0; i < inputEdges.size(); i++)
{
edges[inputEdges[i].first].push_back(inputEdges[i].second);
edges[inputEdges[i].second].push_back(inputEdges[i].first);
}
dfs(0);
return 0;
}
相关文章:
- 提升图:当我的图使用 listS 作为 VertexList 时,如何调用深度优先搜索()?
- 使用迭代深度优先搜索算法的未加权图的最短路径
- 使用后序遍历递归的深度优先搜索会产生意外输出
- 提升图形库 - 深度优先 仅通过连接的顶点进行搜索
- 图上的深度优先搜索算法中的内存泄漏
- 为什么此函数中的运行时错误 C++ 深度优先搜索
- 通过深度优先搜索节点链接到自身进行倾倒.C++
- 矢量迭代器在尝试对图形进行深度优先搜索时导致分割错误 11
- 显示深度优先搜索图遍历C++
- 在C++中实现深度优先搜索
- 深度优先的Minimax分割错误
- 邻接列表中的深度优先或广度算法
- 深度优先图遍历
- 深度优先搜索过早终止
- 深度优先搜索树遍历实现在C++
- 使用邻接矩阵进行深度优先搜索
- 深度优先搜索的实施和改进
- 并行深度优先搜索C++
- 在迭代深度优先搜索(DFS)算法中确定堆栈大小
- 为什么我在这里泄漏内存(深度优先搜索)c ++