链接:https://leetcode-cn.com/problems/find-eventual-safe-states/
解题思路:
- 本题主要是判断图中结点如果在环内那么一定是不安全的,因为环内结点一定存在一条路径是无法到达最终结点的,所以采用DFS+颜色标注进行环的判断
- 注意:
1.颜色标注定义
2.颜色状态转换
class Solution {
public:
vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
int n = graph.size();
vector<int>color(n,0);
function<bool(int)> safe = [&](int x){
if (color[x]>0){
return color[x]==2;
}
color[x]=1;
for(int y : graph[x]){
if (!safe(y)){
return false;
}
}
color[x]=2;
return true;
};
vector<int>res;
for(int i = 0;i<n;++i){
if(safe(i)){
res.emplace_back(i);
}
}
return res;
}
};
class Solution:
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
length = len(graph)
color = [0]*length#0表示没有遍历过,1表示存在环或者正在遍历,2表示安全结点
def safe(x:int):
if color[x] >0:
return color[x]==2
color[x]=1
for y in graph[x]:
if not safe(y):
return False
color[x]=2
return True
return [i for i in range(length) if safe(i)]```