Created
June 9, 2021 19:25
-
-
Save rahulkushwaha12/775da82fa280effce68991d92ea9c544 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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