#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100 // 最大顶点数
// 邻接表的结点
typedef struct Node {
int vertex; // 顶点编号
struct Node* next; // 指向下一个结点的指针
} Node;
// 图的邻接表表示
typedef struct Graph {
int numVertices; // 顶点数量
Node* adjacencyList[MAX_SIZE]; // 邻接表
} Graph;
// 创建一个顶点结点
Node* createNode(int v) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
// 初始化图
Graph* createGraph(int vertices) {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->numVertices = vertices;
for (int i = 0; i < vertices; i++) {
graph->adjacencyList[i] = NULL;
}
return graph;
}
// 添加边
void addEdge(Graph* graph, int src, int dest) {
// 从源顶点添加到目标顶点的边
Node* newNode = createNode(dest);
newNode->next = graph->adjacencyList[src];
graph->adjacencyList[src] = newNode;
// 从目标顶点添加到源顶点的边(因为是无向图)
newNode = createNode(src);
newNode->next = graph->adjacencyList[dest];
graph->adjacencyList[dest] = newNode;
}
// 打印指定顶点的相通顶点
void printConnectedVertices(Graph* graph, int v, int k, int visited[], int distance) {
visited[v] = 1; // 将当前顶点标记为已访问
// 如果当前顶点距离源顶点的路径长度小于等于 k,则打印
if (distance <= k) {
printf("%d ", v);
}
// 递归访问所有与当前顶点相连的顶点
Node* temp = graph->adjacencyList[v];
while (temp != NULL) {
int u = temp->vertex;
// 如果相连的顶点未被访问,则递归调用
if (!visited[u]) {
printConnectedVertices(graph, u, k, visited, distance + 1);
}
temp = temp->next;
}
}
// 打印与指定顶点V0有简单路径相通,且路径长度小于等于k的所有顶点
void printConnectedVerticesWithDistanceLessThanK(Graph* graph, int V0, int k) {
int visited[MAX_SIZE] = { 0 }; // 初始化所有顶点为未访问状态
int distance = 0; // 初始化路径长度为0
printf("与顶点 %d 相通且路径长度小于等于 %d 的顶点有: ", V0, k);
printConnectedVertices(graph, V0, k, visited, distance);
printf("\n");
}
int main() {
// 创建一个邻接表表示的图
Graph* graph = createGraph(7);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 5);
addEdge(graph, 2, 6);
// 打印与顶点0有简单路径相通,且路径长度小于等于2的所有顶点
printConnectedVerticesWithDistanceLessThanK(graph, 0, 2);
return 0;
}