Files
hello-algo/ja/codes/c/chapter_graph/graph_dfs.c
T
Yudong Jin 7257641e0e Retranslate the complete Japanese online edition from Chinese (#2008)
* Retranslate the complete Japanese online edition from Chinese

* Fit Japanese homepage labels and localize heading permalinks

* Point Japanese contribution instructions to the Japanese preview

* Replace locale conditionals with multilingual UI tables
2026-10-30 02:12:26 +08:00

76 lines
2.3 KiB
C

/**
* File: graph_dfs.c
* Created Time: 2023-07-13
* Author: NI-SW ([email protected])
*/
#include "graph_adjacency_list.c"
// ノード数は最大 100 と仮定する
#define MAX_SIZE 100
/* 頂点が訪問済みかどうかを確認する */
int isVisited(Vertex **res, int size, Vertex *vet) {
// 走査してノードを探すため、O(n) の時間を要する
for (int i = 0; i < size; i++) {
if (res[i] == vet) {
return 1;
}
}
return 0;
}
/* 深さ優先走査の補助関数 */
void dfs(GraphAdjList *graph, Vertex **res, int *resSize, Vertex *vet) {
// 訪問した頂点を記録する
res[(*resSize)++] = vet;
// この頂点に隣接する全頂点を走査する
AdjListNode *node = findNode(graph, vet);
while (node != NULL) {
// 訪問済みの頂点をスキップする
if (!isVisited(res, *resSize, node->vertex)) {
// 隣接する頂点を再帰的に訪問する
dfs(graph, res, resSize, node->vertex);
}
node = node->next;
}
}
/* 深さ優先走査 */
// 指定した頂点に隣接する全頂点を取得しやすいように、グラフを隣接リストで表す
void graphDFS(GraphAdjList *graph, Vertex *startVet, Vertex **res, int *resSize) {
dfs(graph, res, resSize, startVet);
}
/* 実行用コード */
int main() {
// 無向グラフを初期化する
int vals[] = {0, 1, 2, 3, 4, 5, 6};
int size = sizeof(vals) / sizeof(vals[0]);
Vertex **v = valsToVets(vals, size);
Vertex *edges[][2] = {{v[0], v[1]}, {v[0], v[3]}, {v[1], v[2]}, {v[2], v[5]}, {v[4], v[5]}, {v[5], v[6]}};
int egdeSize = sizeof(edges) / sizeof(edges[0]);
GraphAdjList *graph = newGraphAdjList();
// すべての頂点と辺を追加する
for (int i = 0; i < size; i++) {
addVertex(graph, v[i]);
}
for (int i = 0; i < egdeSize; i++) {
addEdge(graph, edges[i][0], edges[i][1]);
}
printf("\n初期化後のグラフ\n");
printGraph(graph);
// 深さ優先走査
Vertex *res[MAX_SIZE];
int resSize = 0;
graphDFS(graph, v[0], res, &resSize);
printf("\n深さ優先走査(DFS)の頂点の順序\n");
printArray(vetsToVals(res, resSize), resSize);
// メモリを解放する
delGraphAdjList(graph);
free(v);
return 0;
}