Skip to content

Instantly share code, notes, and snippets.

@rahulkushwaha12
Created June 9, 2021 19:25
Show Gist options
  • Save rahulkushwaha12/775da82fa280effce68991d92ea9c544 to your computer and use it in GitHub Desktop.
Save rahulkushwaha12/775da82fa280effce68991d92ea9c544 to your computer and use it in GitHub Desktop.
package main
func isCyclic(n int, adj [][]int) bool {
vis := make([]bool, n)
var dp = make([]bool, n) //true when all path traversed and with no loop i.e. memoization for no cycles starting this index
for i := 0; i < n; i++ {
if dp[i] {
continue
}
if dfs_util(i, vis, dp, adj) {
return false
}
vis[i] = false
dp[i] = true
}
return true
}
func dfs_util(num int, vis, dp []bool, adj [][]int) bool {
if vis[num] == true {
return true
}
vis[num] = true
for _, n := range adj[num] {
ans := false
if !dp[n] {
ans = dfs_util(n, vis, dp, adj)
}
if ans {
return true
}
vis[n] = false
}
dp[num] = true
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment