【Leetcode】802. Find Eventual Safe States

35 篇文章 2 订阅

In a directed graph, we start at some node and every turn, walk along a directed edge of the graph.  If we reach a node that is terminal (that is, it has no outgoing directed edges), we stop.

Now, say our starting node is eventually safe if and only if we must eventually walk to a terminal node.  More specifically, there exists a natural number K so that for any choice of where to walk, we must have stopped at a terminal node in less than K steps.

Which nodes are eventually safe?  Return them as an array in sorted order.

The directed graph has N nodes with labels 0, 1, ..., N-1, where N is the length of graph.  The graph is given in the following form: graph[i] is a list of labels j such that (i, j) is a directed edge of the graph.

可以用dfs和bfs的方法:

1.dfs的方法:主要通过理解安全点,dfs过程中中间点不是安全点则起点不是安全点,这里安全点可以理解为出发后沿途路径没有环,所以可以设置标记集合,0表示未访问,1表示有环,2表示安全点

class Solution {
public:
    vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
        int color[10001];
        int N=graph.size();
        for(int i=0;i<N;i++) color[i]=0;
        vector<int> ans;
        for(int i=0;i<N;i++){
            if(dfs(i,color,graph)) ans.push_back(i);
        }
        return ans;
    }
        
    bool dfs(int node, int* color, vector<vector<int>>& graph){
        if(color[node]>0) return color[node]==2;
        color[node]=1;
        for(int i=0;i<graph[node].size();i++){
            int x=graph[node][i];
            if(color[x]==1||!dfs(x,color,graph))
                return false;
            if(color[x]==2) continue;
        }
        color[node]=2;
        return true;
    }
};  

bfs方法:先用两个向量维护每个点的出度和入度,出度为 0的明显为安全点加入一个队列中,之后对队列中的每个点,标记为安全点,访问其入度,删除其节点到队列点的边,如果出度为0则加入队列直到队列为空。

class Solution {
public:
    vector<int> eventualSafeNodes(vector<vector<int> >& graph) {
        int n = graph.size();
		bool* ans = new bool[n];
		vector<set<int> > sgraph;
		vector<set<int> > rgraph;
        for(int i=0;i<n;i++) ans[i]=false;
		for(int i=0;i<n;i++){
			set<int> s,p;
			sgraph.push_back(s);
			rgraph.push_back(p);
		}
		queue<int> q;
		for(int i=0;i<n;i++){
			if(graph[i].size()==0) q.push(i);
			  for (int j: graph[i]) {
				sgraph[i].insert(j);
				rgraph[j].insert(i);
			  }
		}

		while(!q.empty()){
			int x=q.front();
			q.pop();
			ans[x]=true;
			
			for(int i:rgraph[x]){
				sgraph[i].erase(x);
				if(sgraph[i].empty()){
					q.push(i);
				}
			}
		}
		vector<int> res;
		for(int i=0;i<n;i++){
			if(ans[i]){
                res.push_back(i);

			}


		}
		return res;


    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值