【Leetcode】802. Find Eventual Safe States

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/KID_LWC/article/details/82110565

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;


    }
};

猜你喜欢

转载自blog.csdn.net/KID_LWC/article/details/82110565