1. 程式人生 > 其它 >2021-8-5 Find Eventual Safe States

2021-8-5 Find Eventual Safe States

難度 中等

題目 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 };