Searching/Depth-First Search
graphrecursivebacktracking
Press play to start
1void dfs(int graph[][MAX], int n, int start) {
2 int visited[MAX] = {0};
3 int stack[MAX], top = -1;
4 stack[++top] = start;
5 while (top >= 0) {
6 int node = stack[top--];
7 if (visited[node]) continue;
8 visited[node] = 1;
9 printf("%d ", node);
10 for (int i = n - 1; i >= 0; i--)
11 if (graph[node][i] && !visited[i]) stack[++top] = i;
12 }
13}
Step 1/0

Practice

LeetCode·#200 Number of IslandsMediumHackerRank·DFS: Connected Cell in a GridMediumNeetCode·Number of IslandsMedium
BestO(V+E)
AverageO(V+E)
WorstO(V+E)
SpaceO(V)