用c语言实现在图中删除顶点操作
时间: 2024-04-12 07:26:52 浏览: 13
以下是使用C语言实现在图中删除顶点的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 100
struct Graph {
int numVertices;
int adjacencyMatrix[MAX_VERTICES][MAX_VERTICES];
};
void initGraph(struct Graph* graph, int numVertices) {
graph->numVertices = numVertices;
// 初始化邻接矩阵
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
graph->adjacencyMatrix[i][j] = 0;
}
}
}
void addEdge(struct Graph* graph, int src, int dest) {
if (src >= 0 && src < graph->numVertices && dest >= 0 && dest < graph->numVertices) {
// 添加边
graph->adjacencyMatrix[src][dest] = 1;
graph->adjacencyMatrix[dest][src] = 1;
}
}
void removeVertex(struct Graph* graph, int vertex) {
if (vertex >= 0 && vertex < graph->numVertices) {
// 删除顶点及其相关的边
for (int i = 0; i < graph->numVertices; i++) {
graph->adjacencyMatrix[vertex][i] = 0;
graph->adjacencyMatrix[i][vertex] = 0;
}
}
}
void printGraph(struct Graph* graph) {
for (int i = 0; i < graph->numVertices; i++) {
printf("%d: ", i);
for (int j = 0; j < graph->numVertices; j++) {
if (graph->adjacencyMatrix[i][j] == 1) {
printf("%d ", j);
}
}
printf("\n");
}
}
int main() {
struct Graph graph;
int numVertices = 4;
initGraph(&graph, numVertices);
// 添加边
addEdge(&graph, 0, 1);
addEdge(&graph, 1, 2);
addEdge(&graph, 2, 3);
addEdge(&graph, 3, 0);
printf("原始图:\n");
printGraph(&graph);
// 删除顶点2及其相关的边
removeVertex(&graph, 2);
printf("\n删除顶点2后的图:\n");
printGraph(&graph);
return 0;
}
```
在上述示例代码中,我们使用邻接矩阵来表示图。`initGraph`函数用于初始化图,`addEdge`函数用于添加边,`removeVertex`函数用于删除顶点及其相关的边。`printGraph`函数用于打印图的结构。
执行上述代码后,将会输出如下结果:
```
原始图:
0: 1 3
1: 0 2
2: 1 3
3: 0 2
删除顶点2后的图:
0: 1 3
1: 0
3: 0
```
从结果中可以看出,顶点2及其相关的边已经被成功删除。