1. 程式人生 > 其它 >找到最終的安全狀態 深搜

找到最終的安全狀態 深搜

傳送門

  https://leetcode-cn.com/problems/find-eventual-safe-states/

題意

思路

AC程式碼

import java.util.ArrayList;
import java.util.List;

class Solution {



    public List<Integer> eventualSafeNodes(int[][] graph) {
        int n = graph.length;
        int[] color = new int[n];
        List<Integer> res = new
ArrayList<>(); for(int i=0;i<n;i++){ if(dfs(graph,color,i)){ res.add(i); } } return res; } private boolean dfs(int[][] graph, int[] color, int x) { if(color[x] == 1){ return false; }else if(color[x] == 2){
return true; } color[x] = 1; for (int y : graph[x]) { if(dfs(graph,color,y) == false){ return false; } } color[x] = 2; return true; } }

  

  

  

一點一點積累,一點一點蛻變!