在有向图中, 我们从某个节点和每个转向处开始, 沿着图的有向边走。 如果我们到达的节点是终点 (即它没有连出的有向边), 我们停止。
现在, 如果我们最后能走到终点,那么我们的起始节点是最终安全的。 更具体地说, 存在一个自然数 K, 无论选择从哪里开始行走, 我们走了不到 K 步后必能停止在一个终点。
哪些节点最终是安全的? 结果返回一个有序的数组。
该有向图有 N 个节点,标签为 0, 1, ..., N-1, 其中 N 是 graph 的节点数. 图以以下的形式给出: graph[i] 是节点 j 的一个列表,满足 (i, j) 是图的一条有向边。
示例:
输入:graph = [[1,2],[2,3],[5],[0],[5],[],[]]
输出:[2,4,5,6]
这里是上图的示意图。
Illustration of graph
提示:
graph 节点数不超过 10000.
图的边数不会超过 32000.
每个 graph[i] 被排序为不同的整数列表, 在区间 [0, graph.length - 1] 中选取。
题目理解:从有向node中,找出死环,非死环。即从一个node开始深度搜索,找出所有的路径,如果路径中某个node>=2出现 ,记为死环,此路径所有节点都是死环node。任何一个到达死环node的node都是死环node。
题目本质:dfs问题,从一点开始进行深度搜索,找出路径中所有的点。 记录路径中 所有的 点的状态,如果因为结果而回溯路径所有点,利用返回值进行回溯标记。
应用:找出一条链中的闭环,非闭环以及能进入 闭环的node。
如果一个问题因为结果影响 路径,则利用此法 层层递归返回return 结果。
问题:返回状态 0/1注意位置,要不然串结果了。 已经闭环/不闭环 是最终走到 最后的状态,所以无需再次走一遍,提前判断终止。 深度递归跟广度递归的区别是深度递归是环重要,先把环走完,进行处理,再走广度。
package com.jd.jr.nlp;
import java.util.ArrayList;
import java.util.List;
/***
* 1.遍历有向图的节点
* 2.对每个节点进行dfs,关系判断
* 3.关系:初始状态,访问过一次,
*
* state 0 初始化 1 访问过一次 2 没问题 3 成环
*/
public class Solution802Diy {
private int dfs(int[][] graph,int index,int[] states){
if(states[index]==1){
// states[index]=3;
return 3;
}
if(states[index]!=0){
return states[index];
}
if(states[index]==0){
states[index]=1;
}
//
// if(states[index]==2){
// return 2;
// }
// if(states[index]==3){
// return 3;
// }
for(int i:graph[index]){
if(this.dfs(graph,i,states)==3){
states[i]=3;
return 3;
};
}
states[index]=2;
return 2;
}
public List<Integer> eventualSafeNodes(int[][] graph) {
List<Integer> ans=new ArrayList<>();
int[] states=new int[graph.length];
for(int i=0;i<graph.length;i++){
if(this.dfs(graph,i,states)==2){
ans.add(i);
}
}
return ans;
}
public static void main(String[] args){
// [[1,2],[2,3],[5],[0],[5],[],[]]
int[][] graph=new int[7][];
graph[0]=new int[]{1,2};
graph[1]=new int[]{2,3};
graph[2]=new int[]{5};
graph[3]=new int[]{0};
graph[4]=new int[]{5};
graph[5]=new int[]{};
graph[6]=new int[]{};
Solution802Diy solution802Std=new Solution802Diy();
List<Integer> result=solution802Std.eventualSafeNodes(graph);
System.out.println(result);
}
}