用C语言编写:从键盘输入创建一个有向图G,以十字链表形式存储在内存中,试写一个判断该有向图中是否有环路(回路)的算法
时间: 2024-04-16 22:26:37 浏览: 79
好的,我们可以修改上面的代码来实现从键盘输入创建有向图的功能。下面是修改后的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Vertex {
int data;
struct ArcNode* first_in;
struct ArcNode* first_out;
} Vertex;
typedef struct ArcNode {
struct Vertex* tail_vertex;
struct Vertex* head_vertex;
struct ArcNode* next_in;
struct ArcNode* next_out;
} ArcNode;
void createGraph(Vertex** graph, int num_vertices) {
*graph = (Vertex*)malloc(num_vertices * sizeof(Vertex));
for (int i = 0; i < num_vertices; i++) {
(*graph)[i].data = i;
(*graph)[i].first_in = NULL;
(*graph)[i].first_out = NULL;
}
}
void addArc(Vertex* graph, int tail, int head) {
ArcNode* arc = (ArcNode*)malloc(sizeof(ArcNode));
arc->tail_vertex = &graph[tail];
arc->head_vertex = &graph[head];
arc->next_in = graph[head].first_in;
graph[head].first_in = arc;
arc->next_out = graph[tail].first_out;
graph[tail].first_out = arc;
}
int hasCycle(Vertex* graph, int num_vertices) {
int* visited = (int*)malloc(num_vertices * sizeof(int));
for (int i = 0; i < num_vertices; i++) {
visited[i] = 0;
}
for (int i = 0; i < num_vertices; i++) {
if (!visited[i]) {
if (hasCycleUtil(graph, visited, i)) {
free(visited);
return 1;
}
}
}
free(visited);
return 0;
}
int hasCycleUtil(Vertex* graph, int* visited, int vertex) {
visited[vertex] = 1;
ArcNode* arc = graph[vertex].first_out;
while (arc != NULL) {
int next_vertex = arc->head_vertex->data;
if (!visited[next_vertex] && hasCycleUtil(graph, visited, next_vertex)) {
return 1;
} else if (visited[next_vertex]) {
return 1;
}
arc = arc->next_out;
}
visited[vertex] = 0;
return 0;
}
int main() {
int num_vertices;
printf("Enter the number of vertices: ");
scanf("%d", &num_vertices);
Vertex* graph;
createGraph(&graph, num_vertices);
int num_arcs;
printf("Enter the number of arcs: ");
scanf("%d", &num_arcs);
printf("Enter the arcs (tail vertex and head vertex):\n");
for (int i = 0; i < num_arcs; i++) {
int tail, head;
scanf("%d %d", &tail, &head);
addArc(graph, tail, head);
}
int has_cycle = hasCycle(graph, num_vertices);
if (has_cycle) {
printf("The graph has a cycle.\n");
} else {
printf("The graph does not have a cycle.\n");
}
return 0;
}
```
这段代码会先要求用户输入顶点的数量,然后根据顶点数量创建一个有向图。接下来,要求用户输入边的数量,并提示用户输入每条边的起点和终点。最后,算法会判断图中是否存在环路,并输出结果。
希望对你有所帮助!如果还有其他问题,请随时提问。
阅读全文