ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

2021-8-5 Find Eventual Safe States

2021-08-05 21:32:47  阅读:186  来源: 互联网

标签:node return graph Safe States vis vector 2021 节点


难度 中等

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

 

标签:node,return,graph,Safe,States,vis,vector,2021,节点
来源: https://www.cnblogs.com/lovetianyi/p/15105428.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有