java: add «802. Find Eventual Safe States»

URL:	https://leetcode.com/problems/find-eventual-safe-states/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-01-24 17:45:57 +01:00
parent c5653d345f
commit 3c9810e7de
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,60 @@
class Solution {
private static class DFS {
private int[][] graph;
private boolean[] visited;
private boolean[] open;
public DFS(int[][] graph) {
this.graph = graph;
visited = new boolean[graph.length];
open = new boolean[graph.length];
}
public boolean hasInCycle(int u) {
return open[u];
}
public boolean run(int u) {
if (open[u]) {
// found loop
return true;
}
if (visited[u]) {
// searched vertex
return false;
}
visited[u] = true;
open[u] = true;
for (var v : graph[u]) {
if (run(v)) {
// loops stay open
return true;
}
}
open[u] = false;
return false;
}
}
public List<Integer> eventualSafeNodes(int[][] graph) {
int n = graph.length;
var runner = new DFS(graph);
for (var i = 0; i < n; ++i) {
runner.run(i);
}
var safe = new ArrayList<Integer>();
for (var i = 0; i < n; ++i) {
if (!runner.hasInCycle(i)) {
safe.add(i);
}
}
return safe;
}
}