码迷,mamicode.com
首页 > 其他好文 > 详细

802. Find Eventual Safe States

时间:2018-05-03 15:20:53      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:turn   states   sha   har   str   esc   lin   else   ack   

https://leetcode.com/problems/find-eventual-safe-states/description/

class Solution {
public:
    vector<bool> visited;
    vector<int> mem;    // -1 unknown, 0 unsafe, 1 safe.
    int n;
    vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
        n = graph.size();
        mem = vector<int>(n, -1);
        visited = vector<bool>(n, false);
        for (int i = 0; i < n; i++)
            dfs(graph, i);
        
        vector<int> res;
        for (int i = 0; i < n; i++)
            if (mem[i] == 1)
                res.push_back(i);
        return res;
    }
    bool dfs(vector<vector<int>>& graph, int i) {
        // check if i is evetually safe
        if (mem[i] != -1)   return mem[i] == 1;
        
        bool res = true;
        if (visited[i]) {  // A loop
            res = false;
        }
        else {
            visited[i] = true;
            for (auto j : graph[i]) {
                if (!dfs(graph, j)) {
                    res = false;
                    break;
                }
            }
            // visited[i] = false;    // This line is optional, since we‘ve cached the result for i in mem.
        }
        mem[i] = res;
        return res;
    }
};

  

802. Find Eventual Safe States

标签:turn   states   sha   har   str   esc   lin   else   ack   

原文地址:https://www.cnblogs.com/JTechRoad/p/8985136.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!