简体   繁体   中英

Graph traversal to reach destination vertex

I've solved the following question that asked to find all the paths that go from 0th node to n-1 node. The code works fine however I'm confused about the time complexity of the solution. I calculated the time complexity of the following code to be O(V+E) where V is the vertices & E is the edges between vertices. And since in DFS we're going through V vertices & each Vertex can have E edges, I think the TC is O(V+E)

However according to leetcode solution section, the time complexity for this algorithm is O(2^N-1 x N). I don't really understand how leetcode came up with this TC. I don't think the leetcode's time complexity is the correct time complexity for the following code.

Can someone please help me figure out the time complexity?

Leetcode question link: https://leetcode.com/problems/all-paths-from-source-to-target/

Question Description:

Given a directed acyclic graph of N nodes. Find all possible paths from node 0 to node N-1, and return them in any order. The graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. graph[i] is a list of all nodes j for which the edge (i, j) exists.

Example image:

在此处输入图片说明

public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        path.add(0);
        
        dfs(graph, result, path, 0);
        
        return result;
    }

    private void dfs(int[][] graph, List<List<Integer>> result, List<Integer> path, int node) {
        if(node == graph.length-1) {
            result.add(new ArrayList<>(path));
            return;
        }
        
        int[] edges = graph[node];
        
        for(int edge : edges) {
            
            path.add(edge);
            
            dfs(graph, result, path, edge);
            
            path.remove(path.size()-1);
        }
    }

Imagine the worst case that we have node-1 to node-N, and node-i linked to node-j if i < j. There are 2^(N-2) paths and (N+2)*2^(N-3) nodes in all paths. We can roughly say O(2^N). To further prove this, these posts may help : Java Iterative with Stack and Queue, and statistics comparing Iterative vs Recursive speeds and what's the time complexity / space complexity for this solution?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM