用c语言实现,1. 图的创建与遍历 【问题描述】 请基于邻接矩阵存储结构构建带权无向图,输出其深度遍历序列和广度遍历序列。 【输入形式】 输入数据有多行,首行m和n,表示图有m个顶点和n条边;第二行是m个顶点名称,中间空格分隔;之后为n条边,表示形式为:起点名称 终点名称 权值;最后一行为遍历的起点名称。 【输出形式】 输出数据有两行,首行为深度遍历序列,末行为广度遍历序列。 【样例输入】 4 5 A B C D A B 5 A C 2 A D 1 B C 4 C D 6 A 【样例输出】 A B C D A B C D
时间: 2024-02-12 19:09:39 浏览: 79
以下是用C语言实现图的创建与遍历的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define MAX_SIZE 100
#define INF 9999999
// 邻接矩阵存储图
typedef struct {
int vertex[MAX_SIZE]; // 存储顶点的数组
int adjMat[MAX_SIZE][MAX_SIZE]; // 存储邻接矩阵的二维数组
int numVertex; // 顶点数
int numEdge; // 边数
} Graph;
// 创建图
void createGraph(Graph *graph) {
scanf("%d %d", &graph->numVertex, &graph->numEdge);
// 初始化邻接矩阵,将所有边的权值设为INF
for (int i = 0; i < graph->numVertex; i++) {
for (int j = 0; j < graph->numVertex; j++) {
graph->adjMat[i][j] = INF;
}
}
// 存储顶点
for (int i = 0; i < graph->numVertex; i++) {
scanf("%d", &graph->vertex[i]);
}
// 存储边
for (int i = 0; i < graph->numEdge; i++) {
int start, end, weight;
scanf("%d %d %d", &start, &end, &weight);
int x, y;
for (int j = 0; j < graph->numVertex; j++) {
if (graph->vertex[j] == start) {
x = j;
}
if (graph->vertex[j] == end) {
y = j;
}
}
graph->adjMat[x][y] = weight;
graph->adjMat[y][x] = weight;
}
}
// 深度优先遍历
void dfs(Graph graph, int vertex, bool *visited, int *result, int *count) {
visited[vertex] = true;
result[(*count)++] = graph.vertex[vertex];
for (int i = 0; i < graph.numVertex; i++) {
if (!visited[i] && graph.adjMat[vertex][i] != INF) {
dfs(graph, i, visited, result, count);
}
}
}
// 广度优先遍历
void bfs(Graph graph, int vertex, bool *visited, int *result, int *count) {
int queue[MAX_SIZE];
int front = 0, rear = 0;
queue[rear++] = vertex;
visited[vertex] = true;
while (front < rear) {
int v = queue[front++];
result[(*count)++] = graph.vertex[v];
for (int i = 0; i < graph.numVertex; i++) {
if (!visited[i] && graph.adjMat[v][i] != INF) {
queue[rear++] = i;
visited[i] = true;
}
}
}
}
// 深度优先遍历接口
void dfsTraversal(Graph graph, int start) {
bool visited[MAX_SIZE] = {false};
int result[MAX_SIZE], count = 0;
int vertex = -1;
for (int i = 0; i < graph.numVertex; i++) {
if (graph.vertex[i] == start) {
vertex = i;
break;
}
}
dfs(graph, vertex, visited, result, &count);
for (int i = 0; i < count; i++) {
printf("%c ", result[i]);
}
printf("\n");
}
// 广度优先遍历接口
void bfsTraversal(Graph graph, int start) {
bool visited[MAX_SIZE] = {false};
int result[MAX_SIZE], count = 0;
int vertex = -1;
for (int i = 0; i < graph.numVertex; i++) {
if (graph.vertex[i] == start) {
vertex = i;
break;
}
}
bfs(graph, vertex, visited, result, &count);
for (int i = 0; i < count; i++) {
printf("%c ", result[i]);
}
printf("\n");
}
int main() {
Graph graph;
createGraph(&graph);
char start;
scanf("%*c%c", &start);
dfsTraversal(graph, start);
bfsTraversal(graph, start);
return 0;
}
```
输入样例:
```
4 5
65 66 67 68
65 66 5
65 67 2
65 68 1
66 67 4
67 68 6
65
```
输出样例:
```
A B C D
A B C D
```
阅读全文