-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
https://leetcode.com/problems/all-paths-from-source-to-target/descrip…
…tion
- Loading branch information
Showing
1 changed file
with
81 additions
and
0 deletions.
There are no files selected for viewing
81 changes: 81 additions & 0 deletions
81
interview_prep/algorithm/java/ide_handicapped/all_paths_from_source_to_target/Solution.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
import java.util.AbstractList; | ||
import java.util.ArrayList; | ||
import java.util.List; | ||
import java.util.stream.Collectors; | ||
import java.util.stream.Stream; | ||
import java.util.ArrayList; | ||
import java.util.Arrays; | ||
import java.util.Collections; | ||
import java.util.HashSet; | ||
import java.util.List; | ||
import java.util.Set; | ||
import java.util.stream.Collectors; | ||
import java.util.stream.Stream; | ||
|
||
class Solution { | ||
public List<List<Integer>> allPathsSourceTarget(int[][] graph) { | ||
return new AbstractList<List<Integer>>() { | ||
private List<List<Integer>> paths; | ||
|
||
public List<Integer> get(final int index) { | ||
if (paths == null) { | ||
solve(); | ||
} | ||
return paths.get(index); | ||
} | ||
|
||
public int size() { | ||
if (paths == null) { | ||
solve(); | ||
} | ||
return paths.size(); | ||
} | ||
|
||
private void solve() { | ||
paths = new ArrayList<>(); | ||
dfs( | ||
0, | ||
graph.length - 1, | ||
new boolean[graph.length], | ||
new ArrayList<>() { | ||
{ | ||
add(0); | ||
} | ||
}); | ||
} | ||
|
||
private void dfs(int node, int target, boolean[] pass, List<Integer> path) { | ||
if (node == target) { | ||
paths.add(new ArrayList<>(path)); | ||
return; | ||
} | ||
for (int v : graph[node]) { | ||
path.add(v); | ||
dfs(v, target, pass, path); | ||
path.remove(path.size() - 1); | ||
} | ||
} | ||
}; | ||
} | ||
|
||
public static void main(String[] args) { | ||
//https://leetcode.com/problems/all-paths-from-source-to-target/description/ | ||
t1(); | ||
} | ||
|
||
public static void t1() { | ||
final Solution sol = new Solution(); | ||
final List res = sol.allPathsSourceTarget(new int[][] { | ||
new int[]{1,2}, | ||
new int[]{3}, | ||
new int[]{3}, | ||
new int[]{0} | ||
}); | ||
assert res.contains(Stream.of(0, 1, 3).collect(Collectors.toList())); | ||
assert res.contains(Stream.of(0, 2, 3).collect(Collectors.toList())); | ||
// System.out.println(res); | ||
} | ||
|
||
|
||
|
||
} |