我们在Graph及其表示中介绍了Graph基础。在这篇文章中,使用了不同的基于STL的表示形式,这有助于使用向量快速实现图形。该实现用于图形的邻接表表示。
以下是具有5个顶点的示例无向图和无权图。
下面是该图的邻接列表表示。
我们在STL中使用向量来使用邻接表表示实现图。
- vector:序列容器。在这里,我们使用它来存储所有顶点的邻接列表。我们使用顶点数作为该向量的索引。
想法是将图表示为向量数组,以使每个向量都代表一个顶点的邻接表。下面是用于DFS遍历的完整的基于STL的C++程序。
C++
// A simple representation of graph using STL,
// for the purpose of competitive programming
#include
using namespace std;
// A utility function to add an edge in an
// undirected graph.
void addEdge(vector adj[], int u, int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
// A utility function to do DFS of graph
// recursively from a given vertex u.
void DFSUtil(int u, vector adj[],
vector &visited)
{
visited[u] = true;
cout << u << " ";
for (int i=0; i adj[], int V)
{
vector visited(V, false);
for (int u=0; u *adj = new vector[V];
vector adj[V];
// Vertex numbers should be from 0 to 4.
addEdge(adj, 0, 1);
addEdge(adj, 0, 4);
addEdge(adj, 1, 2);
addEdge(adj, 1, 3);
addEdge(adj, 1, 4);
addEdge(adj, 2, 3);
addEdge(adj, 3, 4);
DFS(adj, V);
return 0;
}
Python3
# A simple representation of graph using STL,
# for the purpose of competitive programming
# A utility function to add an edge in an
# undirected graph.
def addEdge(adj, u, v):
adj[u].append(v)
adj[v].append(u)
return adj
# A utility function to do DFS of graph
# recursively from a given vertex u.
def DFSUtil(u, adj, visited):
visited[u] = True
print(u, end = " ")
for i in range(len(adj[u])):
if (visited[adj[u][i]] == False):
DFSUtil(adj[u][i], adj, visited)
# This function does DFSUtil() for all
# unvisited vertices.
def DFS(adj, V):
visited = [False]*(V+1)
for u in range(V):
if (visited[u] == False):
DFSUtil(u, adj, visited)
# Driver code
if __name__ == '__main__':
V = 5
# The below line may not work on all
# compilers. If it does not work on
# your compiler, please replace it with
# following
# vector *adj = new vector[V]
adj = [[] for i in range(V)]
# Vertex numbers should be from 0 to 4.
adj = addEdge(adj, 0, 1)
adj = addEdge(adj, 0, 4)
adj = addEdge(adj, 1, 2)
adj = addEdge(adj, 1, 3)
adj = addEdge(adj, 1, 4)
adj = addEdge(adj, 2, 3)
adj = addEdge(adj, 3, 4)
DFS(adj, V)
# This code is contributed by mohit kumar 29.
Javascript
输出 :
0 1 2 3 4
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。