Techniques Used
- DFS
- Graph
- TopologicalSort
Approach
- We maintain a value (0, 1, -1) for each node, such that
- 0 shows the visited nodes
- 1 shows a safe node
- -1 shows a unvisited node
- For every node, check
- if it has already been visited OR is a safe node, just return the safety value of that node.
- if a node does not have any edges going out of it, then mark that node as safe. (marked as 1)
- Now, we only need to concern ourselves with unvisited nodes
- for every edge going out of this current node to a certain child
node
- we run the same function on the child node
- if for any of the child nodes we get a value 0 in return, that means that the current node has a possibility of going into a cycle, so we mark it as unsafe and return
- if the current node is not unsafe after processing all the child
node
, then we mark it simply as safe by making the isSafe
value as 1.
- return the
isSafe[index]
value
Complexity
- Time Complexity: O(N^2)
- Space Complexity: O(N)
Code: Java
class Solution {
public List<Integer> eventualSafeNodes(int[][] graph) {
int n = graph.length;
int[] isSafe = new int[n];
Arrays.fill(isSafe, -1);
List<Integer> res = new ArrayList<>();
for(int i = 0; i < n; i++){
if(checkNode(i, isSafe, graph) == 1){
res.add(i);
}
}
return res;
}
static int checkNode(int index, int[] isSafe, int[][] graph){
if(isSafe[index] != -1) return isSafe[index];
if(graph[index].length == 0) {
isSafe[index] = 1;
return 1;
}
isSafe[index] = 0;
for(int node : graph[index]){
if(checkNode(node, isSafe, graph) == 0){
isSafe[index] = 0;
return 0;
}
}
isSafe[index] = 1;
return isSafe[index];
}
}
Code: C++
class Solution {
public:
vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
int n = graph.size();
vector<int> isSafe (n, -1);
vector<int> result;
for(int i = 0; i < n; i++){
if(checkNode(i, isSafe, graph) == 1){
result.push_back(i);
}
}
return result;
}
int checkNode(int index, vector<int> &isSafe, vector<vector<int>> &graph){
if(isSafe[index] != -1) return isSafe[index];
if(graph[index].size() == 0){
isSafe[index] = 1;
return 1;
}
isSafe[index] = 0;
for(int node: graph[index]){
if(checkNode(node, isSafe, graph) == 0){
isSafe[index] = 0;
return 0;
}
}
isSafe[index] = 1;
return isSafe[index];
}
};