赞
踩
https://leetcode.com/problems/find-eventual-safe-states/
- //开始都是染色为0,2表示是安全无环,1表示有环有毒
- class Solution {
- public:
- bool dfs(int i, vector<int>&color, vector<vector<int>>&graph)
- {
- if(color[i]) return color[i] == 2;
- color[i] = 1; //开始染色为1,不确定是否为安全
- for(auto neighbor: graph[i]){
- if(color[neighbor]==1 || !dfs(neighbor, color, graph)){
- return false;
- }
- }
- color[i] = 2;
- return true;
- }
- vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
- int len = graph.size();
- vector<int> color(len, 0);
- vector<int> ans;
- for(int i=0; i<len; i++){
- if(dfs(i, color, graph)){
- ans.push_back(i);
- }
- }
- return ans;
- }
- };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。