-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
797 All Paths From Source to Target.swift
50 lines (43 loc) · 1.41 KB
/
797 All Paths From Source to Target.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//
// 797 All Paths From Source to Target.swift
// LeetCode-Solutions
//
// Created by Aleksandar Dinic on 24/07/2020.
// Copyright © 2020 Aleksandar Dinic. All rights reserved.
//
import Foundation
/// Source: https://leetcode.com/problems/all-paths-from-source-to-target/
class Solution {
/// Finds all possible paths from node 0 to node N-1.
///
/// - Parameter graph: The graph.
/// - Returns: All possible paths from node 0 to node N-1.
///
/// - Complexity:
/// - time: O(V + E), where V represents the number of vertices and E represents the
/// number of edges.
/// - space: O(V * 2^V), where V represents the number of vertices.
func allPathsSourceTarget(_ graph: [[Int]]) -> [[Int]] {
var dict = [Int: [[Int]]]()
return dfs(graph, node: 0, dict: &dict)
}
private func dfs(_ graph: [[Int]], node: Int, dict: inout [Int: [[Int]]]) -> [[Int]] {
if let path = dict[node] {
return path
}
var ans = [[Int]]()
if node == graph.count - 1 {
ans.append([node])
} else {
for nextNode in graph[node] {
let paths = dfs(graph, node: nextNode, dict: &dict)
for var path in paths {
path.insert(node, at: 0)
ans.append(path)
}
}
}
dict[node] = ans
return ans
}
}