leetcode 802. Find Eventual Safe States | 802. 找到最终的安全状态(有向图DFS)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 802. Find Eventual Safe States | 802. 找到最终的安全状态(有向图DFS)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目
https://leetcode.com/problems/find-eventual-safe-states/
題解
用 circle 表示所有環(huán)上節(jié)點(diǎn)和所有能到達(dá)環(huán)的節(jié)點(diǎn)。
DFS,實(shí)際上每一次遍歷都是像遍歷鏈表一樣,判斷鏈表是否有環(huán),如果有環(huán),則將整個(gè)鏈放進(jìn) circle 中。
有個(gè)剪枝優(yōu)化:如果 DFS 過(guò)程中,遇到了 circle 中的元素,則說(shuō)明之前走過(guò)的路徑也應(yīng)該被放進(jìn) circle 中。
最后,返回所有不在 ciecle 中的元素即可。
class Solution {int N;public List<Integer> eventualSafeNodes(int[][] graph) {N = graph.length;Set<Integer> circle = new HashSet<>();Set<Integer> unCircle = new HashSet<>();for (int i = 0; i < N; i++) {HashSet<Integer> seen = new HashSet<>();seen.add(i);dfs(graph, circle, unCircle, seen, i);}List<Integer> result = new ArrayList<>();for (int i = 0; i < N; i++) {if (!circle.contains(i)) result.add(i);}return result;}public void dfs(int[][] graph, Set<Integer> circle, Set<Integer> unCircle, Set<Integer> seen, int i) {if (circle.contains(i)) {circle.addAll(seen);return;}if (unCircle.contains(i)) {return;}for (int j : graph[i]) {if (seen.contains(j)) {circle.addAll(seen);return;} else {seen.add(j);dfs(graph, circle, unCircle, seen, j);seen.remove(j);}}if (!circle.contains(i)) unCircle.addAll(seen);} }總結(jié)
以上是生活随笔為你收集整理的leetcode 802. Find Eventual Safe States | 802. 找到最终的安全状态(有向图DFS)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: leetcode 476. Number
- 下一篇: Purpose of cmove ins