Topics / Data Structures & Algorithms / Q19
Implement BFS and DFS graph traversal in C.
Short answer: BFS uses a queue; DFS uses recursion or a stack. Mark each vertex when discovered so cycles do not cause repeated visits.
#include <stdio.h>
#include <stdbool.h>
#define N 8
/* Adjacency matrix, vertices 0 to N-1 */
void bfs(const bool g[N][N], int start)
{
bool seen[N] = {0};
int q[N], head = 0, tail = 0;
seen[start] = true;
q[tail++] = start;
while (head < tail) {
int u = q[head++];
printf("%d ", u);
for (int v = 0; v < N; v++)
if (g[u][v] && !seen[v]) {
seen[v] = true;
q[tail++] = v;
}
}
}
void dfs(const bool g[N][N], int u, bool seen[N])
{
seen[u] = true;
printf("%d ", u);
for (int v = 0; v < N; v++)
if (g[u][v] && !seen[v])
dfs(g, v, seen);
}
Pass a valid start index and an initially zeroed seen array to DFS. Both visit the reachable vertices; scan unvisited vertices to cover a disconnected graph. Time O(N²) with a matrix, O(V+E) with adjacency lists. Space O(N) for queue or recursion. For large embedded graphs prefer an explicit bounded stack.