802。找出最終的安全狀態
難度:中
主題:深度優先搜尋、廣度優先搜尋、圖表、拓樸排序
有一個由 n 個節點組成的有向圖,每個節點標記為從 0 到 n - 1。此圖由0 索引 2D 整數陣列圖表示,其中graph[i] 是整數陣列與節點i 相鄰的節點數,意味著從節點i 到graph[i] 中的每個節點都有一條邊。
如果沒有出邊,則節點是終端節點。如果從該節點開始的每條可能路徑都通往終端節點(或另一個安全節點),則該節點是安全節點。
傳回包含圖表的所有安全節點的陣列。答案應依升序順序排序。
範例1:
範例2:
約束:
解:
我們需要辨識圖中的所有安全節點。這涉及檢查是否從給定節點開始,每條路徑最終都會到達終端節點或另一個安全節點。此解決方案使用深度優先搜尋 (DFS) 來檢測循環並將節點分類為安全或不安全。
我們使用具有三種狀態的訪問數組:
讓我們用 PHP 實現這個解決方案:802。找到最終的安全狀態
<?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 函數:
主要功能:
$graph = [[1,2],[2,3],[5],[0],[5],[],[]]; print_r(eventualSafeNodes($graph));
輸出:
[2, 4, 5, 6]
$graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]; print_r(eventualSafeNodes($graph));
輸出:
<?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 有效地確定安全節點,確保滿足問題限制。
聯絡連結
如果您發現本系列有幫助,請考慮在 GitHub 上給 存儲庫
一個星號或在您最喜歡的社交網絡上分享該帖子? 。您的支持對我來說意義重大!如果您想要更多類似的有用內容,請隨時關注我:
以上是。找到最終的安全狀態的詳細內容。更多資訊請關注PHP中文網其他相關文章!