1. DFS Path Simulation from Each Node
Intuition
For every node i, simulate all possible paths using standard DFS. If any path encounters an already visited node on the current path (cycle) or exceeds V steps, node i is not safe. If all branches from i reach terminal nodes, mark i safe.
Algorithm
- Initialize
safeNodes = []. - For each node i from 0 to n - 1:
- Run recursive DFS with a current path set to detect cycles.
- If no cycle is found on any branch departing from i, add i to
safeNodes. - Return
safeNodes.
#include <iostream>#include <vector> bool hasCycle(int u, const std::vector<std::vector<int>>& graph, std::vector<bool>& onPath, std::vector<bool>& visited) { onPath[u] = true; for (int v : graph[u]) { if (onPath[v]) return true; if (!visited[v]) { if (hasCycle(v, graph, onPath, visited)) return true; } } onPath[u] = false; visited[u] = true; return false;} std::vector<int> eventualSafeNodesBrute(std::vector<std::vector<int>>& graph) { int n = graph.size(); std::vector<int> safeNodes; for (int i = 0; i < n; ++i) { std::vector<bool> onPath(n, false); std::vector<bool> visited(n, false); if (!hasCycle(i, graph, onPath, visited)) { safeNodes.push_back(i); } } return safeNodes;} int main() { std::vector<std::vector<int>> graph = {{1,2},{2,3},{5},{0},{5},{},{}}; auto res = eventualSafeNodesBrute(graph); std::cout << "Safe Nodes (Brute): "; for (int x : res) std::cout << x << " "; std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(V * (V + E)) because each node initiates an un-memoized full graph exploration. - Space complexity:
O(V) for the path recursion stack.