在给定图中使用邻接矩阵实现 DFS 遍历的 C 程序
给定一个有V个顶点和E个边的无向图。任务是执行图的DFS 遍历。
例子:
Input: V = 7, E = 7
Connections: 0-1, 0-2, 1-3, 1-4, 1-5, 1-6, 6-2
See the diagram for connections:
Output : 0 1 3 4 5 6 2
Explanation: The traversal starts from 0 and follows the following path 0-1, 1-3, 1-4, 1-5, 1-6, 6-2.
Input: V = 1, E = 0
Output: 0
Explanation: There is no other vertex than 0 itself.
方法:按照下面提到的方法。
- 最初,所有顶点都被标记为未访问(假)。
- DFS 算法从图中的顶点u开始。从顶点u开始,它考虑从u到其他顶点的边。
- 如果边指向已经访问过的顶点,则回溯到当前顶点u 。
- 如果一条边通向一个未访问的顶点,则转到该顶点并从该顶点开始处理。这意味着新顶点成为遍历的当前根。
- 遵循此过程,直到顶点被标记为已访问。
这里使用邻接矩阵来存储顶点之间的连接。
Take the following graph:
The adjacency matrix for this graph is:0 1 1 0 0 0 0 1 0 0 1 1 1 1 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0
下面是简单的深度优先遍历的实现。
C
// C code to implement above approach
#include
#include
// Globally declared visited array
int vis[100];
// Graph structure to store number
// of vertices and edges and
// Adjacency matrix
struct Graph {
int V;
int E;
int** Adj;
};
// Function to input data of graph
struct Graph* adjMatrix()
{
struct Graph* G = (struct Graph*)
malloc(sizeof(struct Graph));
if (!G) {
printf("Memory Error\n");
return NULL;
}
G->V = 7;
G->E = 7;
G->Adj = (int**)malloc((G->V) * sizeof(int*));
for (int k = 0; k < G->V; k++) {
G->Adj[k] = (int*)malloc((G->V) * sizeof(int));
}
for (int u = 0; u < G->V; u++) {
for (int v = 0; v < G->V; v++) {
G->Adj[u][v] = 0;
}
}
G->Adj[0][1] = G->Adj[1][0] = 1;
G->Adj[0][2] = G->Adj[2][0] = 1;
G->Adj[1][3] = G->Adj[3][1] = 1;
G->Adj[1][4] = G->Adj[4][1] = 1;
G->Adj[1][5] = G->Adj[5][1] = 1;
G->Adj[1][6] = G->Adj[6][1] = 1;
G->Adj[6][2] = G->Adj[2][6] = 1;
return G;
}
// DFS function to print DFS traversal of graph
void DFS(struct Graph* G, int u)
{
vis[u] = 1;
printf("%d ", u);
for (int v = 0; v < G->V; v++) {
if (!vis[v] && G->Adj[u][v]) {
DFS(G, v);
}
}
}
// Function for DFS traversal
void DFStraversal(struct Graph* G)
{
for (int i = 0; i < 100; i++) {
vis[i] = 0;
}
for (int i = 0; i < G->V; i++) {
if (!vis[i]) {
DFS(G, i);
}
}
}
// Driver code
void main()
{
struct Graph* G;
G = adjMatrix();
DFStraversal(G);
}
输出
0 1 3 4 5 6 2
时间复杂度: O(V + E)
辅助空间: O(V)