【Leetcode】1059. All Paths from Source Lead to Destination

题目地址:

https://leetcode.com/problems/all-paths-from-source-lead-to-destination/html

给定一个有向图,再给定其中两个点 s s d d ,问从 s s 出发的全部路径是否都能走到 d d 。若是发现了圈的话要返回false,由于这条路径是无限长的,并不会走到 d d ;若是有条路径的终点不是 d d ,也返回false。java

思路是DFS。从 s s 出发搜索全部的路径,搜索的同时看看有没有环,搜索到终点的时候看看有没有到dest,若是发现都没有问题的话,就接着搜索下一条,搜索完全部路径后都没发现问题则返回true。代码以下:web

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution {
    public boolean leadsToDestination(int n, int[][] edges, int source, int destination) {
        Map<Integer, List<Integer>> graph = new HashMap<>();
        for (int[] edge : edges) {
            graph.putIfAbsent(edge[0], new ArrayList<>());
            graph.get(edge[0]).add(edge[1]);
        }
        
        return dfs(source, destination, graph, new boolean[n]);
    }
    
    // 从v出发,判断是否全部路径的终点都是dest,visited记录路径上走过的点
    private boolean dfs(int v, int dest, Map<Integer, List<Integer>> graph, boolean[] visited) {
    	// v没有出度的时候,说明到终点了,判断一下是否发现了终点不等于dest的路径,若是发现了返回false
        if (!graph.containsKey(v)) {
            if (v != dest) {
                return false;
            }
        }
        
        visited[v] = true;
        // 若是v有出度的话,继续DFS
        if (graph.containsKey(v)) {
            for (int next : graph.get(v)) {
            	// 若是发现以前路径上遍历过的顶点,说明有环,不继续遍历了返回false
                if (visited[next]) {
                    return false;
                }
                
                if (!visited[next] && !dfs(next, dest, graph, visited)) {
                    return false;
                }
            }
        }
        
        // 回溯前要恢复现场,以便搜索下一条路径
        visited[v] = false;
        return true;
    }
}

时空复杂度 O ( V + E ) O(V+E) app