Skip to content

Instantly share code, notes, and snippets.

@Desolve
Created June 5, 2023 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Desolve/a0d407e4d47566801d4644afb900a168 to your computer and use it in GitHub Desktop.
Save Desolve/a0d407e4d47566801d4644afb900a168 to your computer and use it in GitHub Desktop.
0802 Find Eventual Safe States
class Solution {
public List<Integer> eventualSafeNodes(int[][] graph) {
int n = graph.length;
int[] vis = new int[n];
int[] path = new int[n];
List<Integer> res = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (vis[i] == 0) {
dfs(i, graph, vis, path);
}
}
for (int i = 0; i < n; i++) {
if (path[i] == 0) {
res.add(i);
}
}
return res;
}
private boolean dfs(int curr, int[][] graph, int[] vis, int[] path) {
vis[curr] = 1;
path[curr] = 1;
for (int u : graph[curr]) {
if (vis[u] == 0) {
if (dfs(u, graph, vis, path)) {
return true;
}
} else if (path[u] == 1) {
return true;
}
}
path[curr] = 0;
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment