今日主要学习了图的两种遍历方法:深度优先遍历和广度优先遍历
深度优先搜索(DFS)

include <stdio.h>

include <stdlib.h>

define MAX_VERTICES 100

// 图的结构体,使用邻接表存储
typedef struct Graph {
int numVertices;
struct AdjListNode** adjLists;
int* visited;
} Graph;

// 邻接表节点结构体
typedef struct AdjListNode {
int dest;
struct AdjListNode* next;
} AdjListNode;

// 创建邻接表节点
AdjListNode* createAdjListNode(int dest) {
AdjListNode* newNode = (AdjListNode*)malloc(sizeof(AdjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}

// 创建图
Graph* createGraph(int numVertices) {
Graph* graph = (Graph)malloc(sizeof(Graph));
graph->numVertices = numVertices;
graph->adjLists = (AdjListNode**)malloc(numVertices * sizeof(AdjListNode
));
graph->visited = (int*)malloc(numVertices * sizeof(int));
for (int i = 0; i < numVertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}

// 添加边
void addEdge(Graph* graph, int src, int dest) {
AdjListNode* newNode = createAdjListNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

// 对于无向图,添加反向边
newNode = createAdjListNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;

}

// 深度优先搜索辅助函数
void DFSUtil(Graph* graph, int vertex) {
graph->visited[vertex] = 1;
printf("%d ", vertex);

AdjListNode* temp = graph->adjLists[vertex];
while (temp!= NULL) {
    if (!graph->visited[temp->dest]) {
        DFSUtil(graph, temp->dest);
    }
    temp = temp->next;
}

}

// 深度优先搜索
void DFS(Graph* graph, int startVertex) {
DFSUtil(graph, startVertex);
}

广度优先搜索(BFS)

include <stdio.h>

include <stdlib.h>

include

// 广度优先搜索
void BFS(Graph* graph, int startVertex) {
int* visited = (int*)malloc(graph->numVertices * sizeof(int));
for (int i = 0; i < graph->numVertices; i++) {
visited[i] = 0;
}

std::queue<int> queue;
visited[startVertex] = 1;
queue.push(startVertex);

while (!queue.empty()) {
    int currentVertex = queue.front();
    queue.pop();
    printf("%d ", currentVertex);

    AdjListNode* temp = graph->adjLists[currentVertex];
    while (temp!= NULL) {
        if (!visited[temp->dest]) {
            visited[temp->dest] = 1;
            queue.push(temp->dest);
        }
        temp = temp->next;
    }
}

}

posted on 2025-01-10 19:05  Swishy  阅读(7)  评论(0)    收藏  举报