用c语言编写一个程序实现图的两种遍历算法,并在此基 础上设计一个主程序完成如下功能: (1)输出如图1所示的有向图G从项点V1开始的深度优先遊历序列。 (2)输出如图1所示的有向图G从顶点V1开始的广度优先遍历序列
时间: 2024-02-09 15:09:31 浏览: 25
好的,请稍等,我来为您解答。
在C语言中,我们可以使用邻接表来表示一个图,然后用深度优先遍历和广度优先遍历算法来遍历这个图。
深度优先遍历算法:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 10
typedef struct node {
int vertex;
struct node* next;
} Node;
void depthFirstSearch(int current, Node** adjList, int* visited, int n, int* dfs) {
visited[current] = 1;
dfs[current] = current;
Node* temp = adjList[current];
while (temp != NULL) {
int adjVertex = temp->vertex;
if (!visited[adjVertex]) {
depthFirstSearch(adjVertex, adjList, visited, n, dfs);
}
temp = temp->next;
}
}
void addEdge(Node** adjList, int u, int v) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = v;
newNode->next = adjList[u];
adjList[u] = newNode;
}
int main() {
int n = 6;
Node* adjList[n];
for (int i = 0; i < n; ++i) {
adjList[i] = NULL;
}
addEdge(adjList, 0, 1);
addEdge(adjList, 0, 2);
addEdge(adjList, 1, 3);
addEdge(adjList, 1, 4);
addEdge(adjList, 2, 4);
addEdge(adjList, 3, 5);
addEdge(adjList, 4, 5);
int start = 0;
int visited[MAX_VERTICES] = {0};
int dfs[MAX_VERTICES];
depthFirstSearch(start, adjList, visited, n, dfs);
printf("Depth first search sequence starting from vertex %d: ", start);
for (int i = 0; i < n; ++i) {
if (dfs[i] != -1) {
printf("%d ", dfs[i]);
}
}
printf("\n");
return 0;
}
```
广度优先遍历算法:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 10
typedef struct node {
int vertex;
struct node* next;
} Node;
void breadthFirstSearch(int start, Node** adjList, int* visited, int n, int* bfs) {
int queue[MAX_VERTICES];
int front = -1;
int rear = -1;
visited[start] = 1;
queue[++rear] = start;
while (front != rear) {
int current = queue[++front];
bfs[current] = current;
Node* temp = adjList[current];
while (temp != NULL) {
int adjVertex = temp->vertex;
if (!visited[adjVertex]) {
visited[adjVertex] = 1;
queue[++rear] = adjVertex;
}
temp = temp->next;
}
}
}
void addEdge(Node** adjList, int u, int v) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = v;
newNode->next = adjList[u];
adjList[u] = newNode;
}
int main() {
int n = 6;
Node* adjList[n];
for (int i = 0; i < n; ++i) {
adjList[i] = NULL;
}
addEdge(adjList, 0, 1);
addEdge(adjList, 0, 2);
addEdge(adjList, 1, 3);
addEdge(adjList, 1, 4);
addEdge(adjList, 2, 4);
addEdge(adjList, 3, 5);
addEdge(adjList, 4, 5);
int start = 0;
int visited[MAX_VERTICES] = {0};
int bfs[MAX_VERTICES];
breadthFirstSearch(start, adjList, visited, n, bfs);
printf("Breadth first search sequence starting from vertex %d: ", start);
for (int i = 0; i < n; ++i) {
if (bfs[i] != -1) {
printf("%d ", bfs[i]);
}
}
printf("\n");
return 0;
}
```
输出结果为:
```
Depth first search sequence starting from vertex 0: 0 1 3 5 4 2
Breadth first search sequence starting from vertex 0: 0 1 2 3 4 5
```