-
Notifications
You must be signed in to change notification settings - Fork 0
/
PossibleClass.java
52 lines (39 loc) · 1.32 KB
/
PossibleClass.java
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
51
52
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class PossibleClass {
List<List<Integer>> resPath = new LinkedList<>();
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<Integer>[] adj = new ArrayList[graph.length];
for(int i = 0; i<graph.length; i++){
adj[i] = new ArrayList<Integer>();
for(int j = 0; j<graph[i].length; j++){
adj[i].add(graph[i][j]);
}
}
boolean[] visited = new boolean[adj.length];
LinkedList<Integer> path = new LinkedList<Integer>();
traverse(adj,visited,0,path);
return resPath;
}
public void traverse(List<Integer>[] adj, boolean[] visited, int node, LinkedList<Integer> path){
// if(visited[node]){
// return;
// }
// visited[node] = true;
path.add(node);
int l = adj.length;
if(node == l-1){
// System.out.println("yes");
resPath.add(new LinkedList<>(path));
// System.out.println(resPath);
path.removeLast();
return;
}
for(int neighbor: adj[node]){
// System.out.println(neighbor);
traverse(adj,visited,neighbor, path);
}
path.removeLast();
}
}