是否有回路 分数 25 作者 陈越 单位 浙江大学 如果有向图用邻接表表示,试设计算法判断图中是否存在回路
时间: 2025-07-05 18:09:19 浏览: 7
### 判断有向图中是否存在回路的算法设计
对于给定的一个有向图 \( G \),可以采用深度优先搜索(DFS)的方法来检测图中是否存在回路。这种方法的核心在于利用颜色标记节点的状态,从而追踪访问路径并识别循环。
#### 使用 DFS 检测回路的具体实现如下:
定义三种状态用于标记节点的颜色:
- 白色 (`WHITE`):尚未被发现。
- 灰色 (`GRAY`):正在探索其相邻节点。
- 黑色 (`BLACK`):已完成探索。
当遇到灰色节点时,则说明存在一条从当前节点出发能够回到自身的路径,即发现了回路。
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 100 // 假设最大顶点数为100
typedef enum { WHITE, GRAY, BLACK } Color;
// 定义邻接表结构体
typedef struct Node {
int vertex;
struct Node* next;
} Node;
Node *adjList[MAX_VERTICES]; // 邻接表数组
Color color[MAX_VERTICES];
int n; // 节点数量
void addEdge(int u, int v) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = v;
newNode->next = adjList[u];
adjList[u] = newNode;
}
int hasCycleUtil(int node) {
color[node] = GRAY;
Node* temp = adjList[node];
while (temp != NULL) {
if (color[temp->vertex] == WHITE && hasCycleUtil(temp->vertex)) {
return 1;
}
else if (color[temp->vertex] == GRAY) {
return 1;
}
temp = temp->next;
}
color[node] = BLACK;
return 0;
}
int detectCycle() {
for (int i = 0; i < n; ++i) {
color[i] = WHITE;
}
for (int i = 0; i < n; ++i++) {
if (color[i] == WHITE && hasCycleUtil(i))
return 1;
}
return 0;
}
```
上述代码实现了基于邻接表表示的有向图中的回路检测功能[^1]。此方法的时间复杂度接近于 O(V+E),其中 V 是顶点的数量而 E 是边的数量。
阅读全文
相关推荐


















