802. Find Eventual Safe States #1218
-
Topics: There is a directed graph of A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node). Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order. Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to identify all the safe nodes in the graph. This involves checking if starting from a given node, every path eventually reaches a terminal node or another safe node. The solution uses Depth-First Search (DFS) to detect cycles and classify nodes as safe or unsafe. Key Insights:
Approach:
We use a
Steps:
Let's implement this solution in PHP: 802. Find Eventual Safe States <?php
/**
* @param Integer[][] $graph
* @return Integer[]
*/
function eventualSafeNodes($graph) {
$n = count($graph);
$visited = array_fill(0, $n, 0); // 0: unvisited, 1: visiting, 2: safe
// Check every node for safety
$safeNodes = [];
for ($i = 0; $i < $n; $i++) {
if (dfs($i, $graph, $visited) == 2) {
$safeNodes[] = $i;
}
}
return $safeNodes;
}
/**
* DFS helper function
*
* @param $node
* @param $graph
* @param $visited
* @return int|mixed
*/
function dfs($node, $graph, &$visited) {
if ($visited[$node] != 0) {
return $visited[$node]; // Return the state (safe or unsafe)
}
$visited[$node] = 1; // Mark the node as visiting
foreach ($graph[$node] as $neighbor) {
// If the neighbor leads to an unsafe node, current node is unsafe
if (dfs($neighbor, $graph, $visited) == 1) {
$visited[$node] = 1;
return 1;
}
}
$visited[$node] = 2; // Mark the node as safe
return 2;
}
// Example usage:
$graph1 = [[1,2],[2,3],[5],[0],[5],[],[]];
$graph2 = [[1,2,3,4],[1,2],[3,4],[0,4],[]];
print_r(eventualSafeNodes($graph1)) . "\n"; // Output: [2,4,5,6]
print_r(eventualSafeNodes($graph2)) . "\n"; // Output: [4]
?> Explanation:
Example Walkthrough:Example 1:$graph = [[1,2],[2,3],[5],[0],[5],[],[]];
print_r(eventualSafeNodes($graph));
Output:
Example 2:$graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]];
print_r(eventualSafeNodes($graph));
Output:
Time and Space Complexity:
This solution efficiently determines the safe nodes using DFS, ensuring that the problem constraints are met. |
Beta Was this translation helpful? Give feedback.
We need to identify all the safe nodes in the graph. This involves checking if starting from a given node, every path eventually reaches a terminal node or another safe node. The solution uses Depth-First Search (DFS) to detect cycles and classify nodes as safe or unsafe.
Key Insights:
Approach: