package main import "fmt" func dfs(graph map[int][]int, start int, visited map[int]bool, result *[]int) { visited[start] = true *result = append(*result, start) for _, neighbor := range graph[start] { if !visited[neighbor] { dfs(graph, neighbor, visited, result) } } } func main() { graph := map[int][]int{ 1: {2, 3}, 2: {4}, 3: {}, 4: {}, } visited := make(map[int]bool) var result []int dfs(graph, 1, visited, &result) fmt.Println(result) }
The DFS starts at node 1, visits 2 first, then 4 (neighbor of 2), backtracks to 1, then visits 3.
graph := map[int][]int{ 0: {1, 2}, 1: {2}, 2: {0, 3}, 3: {3}, 4: {5}, 5: {}, }
Starting from node 0, DFS visits nodes 0,1,2,3. Nodes 4 and 5 are disconnected and not visited.
func dfs(graph map[int][]int, start int, visited map[int]bool, result *[]int) { visited[start] = true *result = append(*result, start) for _, neighbor := range graph[start] { if visited[neighbor] { dfs(graph, neighbor, visited, result) } } }
The condition incorrectly recurses when the neighbor is already visited, causing infinite recursion and stack overflow.
graph := map[string][]string{ "A": {"B", "C"}, "B": {"D", "E"}, "C": {"F"}, "D": {"B"}, "E": {}, "F": {"C"}, } visited := make(map[string]bool) var result []string var dfs func(string) dfs = func(node string) { visited[node] = true result = append(result, node) for _, neighbor := range graph[node] { if !visited[neighbor] { dfs(neighbor) } } } dfs("A") fmt.Println(result)
DFS visits A, then B, then D (neighbor of B), then E, backtracks to A, then visits C, then F.
Option D starts DFS from one arbitrary node and checks if all nodes are visited, correctly determining connectivity.
Option D runs DFS multiple times unnecessarily.
Option D assumes node 0 exists, which may not be true.
Option D runs DFS from every node, marking all visited but not checking connectivity properly.
