难度 中等
题目 Leetcode:
Find Eventual Safe States
We start at some node in a directed graph, and every turn, we walk along a directed edge of the graph. If we reach a terminal node (that is, it has no outgoing directed edges), we stop.
We define a starting node to be safe if we must eventually walk to a terminal node. More specifically, there is a natural number k, so that we must have stopped at a terminal node in less than k steps for any choice of where to walk.
Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.
The directed graph has n nodes with labels from 0 to 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, going from node i to node j.
题目解析
本题的用到了深搜也就是dfs。
具体思路就是,如果访问当前节点的子节点时访问到一个非安全节点,那么当前节点就是不安全的,不安全的节点标记为1;如果当前节点的所有子节点都是安全的那么当前节点是安全的,安全的节点也就标记为2。
解析完毕,以下是参考代码:
1 class Solution { 2 public: 3 vector<int> vis; 4 bool dfs(const vector<vector<int>>& graph, int x) 5 { 6 if(vis[x]) 7 { 8 if(vis[x] == 1)return false; 9 else return true; 10 } 11 vis[x] = 1; 12 for(int j : graph[x]) 13 { 14 if(dfs(graph, j))vis[j] = 2; 15 else return false; 16 } 17 return true; 18 } 19 vector<int> eventualSafeNodes(vector<vector<int>>& graph) { 20 int n = graph.size(); 21 vis.resize(n, 0); 22 vector<int> ans; 23 for(int i = 0; i < n; i++) 24 { 25 if(dfs(graph, i)) 26 { 27 ans.push_back(i); 28 vis[i] = 2; 29 } 30 } 31 return ans; 32 } 33 };