802. Find Eventual Safe States
Difficulty: Medium
Topics: Depth-First Search, Breadth-First Search, Graph, Topological Sort
There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].
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:
Solution:
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.
We use a visited array with three states:
Let's implement this solution in PHP: 802. Find Eventual Safe States
<?php /** * @param Integer[][] $graph * @return Integer[] */ function eventualSafeNodes($graph) { ... ... ... /** * go to ./solution.php */ } /** * DFS helper function * * @param $node * @param $graph * @param $visited * @return int|mixed */ function dfs($node, $graph, &$visited) { ... ... ... /** * go to ./solution.php */ } // 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] ?>
DFS Function:
Main Function:
$graph = [[1,2],[2,3],[5],[0],[5],[],[]]; print_r(eventualSafeNodes($graph));
Output:
[2, 4, 5, 6]
$graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]; print_r(eventualSafeNodes($graph));
Output:
<?php /** * @param Integer[][] $graph * @return Integer[] */ function eventualSafeNodes($graph) { ... ... ... /** * go to ./solution.php */ } /** * DFS helper function * * @param $node * @param $graph * @param $visited * @return int|mixed */ function dfs($node, $graph, &$visited) { ... ... ... /** * go to ./solution.php */ } // 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] ?>
This solution efficiently determines the safe nodes using DFS, ensuring that the problem constraints are met.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of . Find Eventual Safe States. For more information, please follow other related articles on the PHP Chinese website!