package main import "fmt" func dfs(node int, graph map[int][]int, visited, recStack map[int]bool) bool { visited[node] = true recStack[node] = true for _, neighbor := range graph[node] { if !visited[neighbor] { if dfs(neighbor, graph, visited, recStack) { return true } } else if recStack[neighbor] { return true } } recStack[node] = false return false } func hasCycle(graph map[int][]int) bool { visited := make(map[int]bool) recStack := make(map[int]bool) for node := range graph { if !visited[node] { if dfs(node, graph, visited, recStack) { return true } } } return false } func main() { graph := map[int][]int{ 1: {2}, 2: {3}, 3: {4}, 4: {2}, } fmt.Println(hasCycle(graph)) }
The graph has edges 1->2, 2->3, 3->4, and 4->2. The edge 4->2 creates a cycle involving nodes 2, 3, and 4. The DFS detects this cycle and returns true.
package main import "fmt" func dfs(node int, graph map[int][]int, visited, recStack map[int]bool) bool { visited[node] = true recStack[node] = true for _, neighbor := range graph[node] { if !visited[neighbor] { if dfs(neighbor, graph, visited, recStack) { return true } } else if recStack[neighbor] { return true } } recStack[node] = false return false } func hasCycle(graph map[int][]int) bool { visited := make(map[int]bool) recStack := make(map[int]bool) for node := range graph { if !visited[node] { if dfs(node, graph, visited, recStack) { return true } } } return false } func main() { graph := map[int][]int{ 1: {2}, 2: {3}, 3: {4}, 4: {}, } fmt.Println(hasCycle(graph)) }
The graph edges are 1->2, 2->3, 3->4, and 4 has no outgoing edges. There is no cycle, so the function returns false.
package main import "fmt" func dfs(node int, graph map[int][]int, visited map[int]bool) bool { visited[node] = true for _, neighbor := range graph[node] { if !visited[neighbor] { if dfs(neighbor, graph, visited) { return true } } else { return true } } return false } func hasCycle(graph map[int][]int) bool { visited := make(map[int]bool) for node := range graph { if !visited[node] { if dfs(node, graph, visited) { return true } } } return false } func main() { graph := map[int][]int{ 1: {2}, 2: {3}, 3: {1}, } fmt.Println(hasCycle(graph)) }
The code lacks a recursion stack to differentiate between nodes currently in the recursion path and fully visited nodes. However, in this graph, the cycle 1->2->3->1 is detected because a visited neighbor is found during DFS, so it returns true.
The recursion stack helps identify back edges, which are edges pointing to nodes currently in the recursion path. These back edges indicate a cycle in directed graphs.
There are three distinct cycles:
1) 1 -> 2 -> 3 -> 1
2) 3 -> 4 -> 5 -> 3
3) 6 -> 7 -> 6
