-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathAllPathstoTarget.java
78 lines (72 loc) · 1.9 KB
/
AllPathstoTarget.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class AllPathsToTarget {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
Graph G = new Graph(graph.length);
for (int i=0;i<graph.length;i++)
{
for (int j=0;j<graph[i].length;j++)
{
G.addEdge(i,graph[i][j]);
}
}
List<List<Integer>> ans = new ArrayList<>();
int source = 0;
ArrayList<Integer> temp = new ArrayList<>();
temp.add(0);
dfs(source,graph,ans,temp);
return ans;
}
public void dfs(int start, int[][] graph, List<List<Integer>> l, ArrayList<Integer> path)
{
if (start==graph.length-1)
{
l.add(new ArrayList<>(path));
return ;
}
for (int i=0;i<graph[start].length;i++)
{
path.add(graph[start][i]);
dfs(graph[start][i],graph,l,path);
path.remove(path.size()-1);
}
}
}
class Graph
{
public int V;
public boolean[] visited;
public ArrayList<ArrayList<Integer>> adj;
// Constructor
public Graph(int v)
{
V = v;
visited = new boolean[V];
adj = new ArrayList<>();
for (int i=0; i<v; ++i)
adj.add(new ArrayList<>());
}
// Function to add an edge into the graph
public void addEdge(int v,int w)
{
adj.get(v).add(w);
}
public void BFS(int s)
{
LinkedList<Integer> queue = new LinkedList<Integer>();
visited[s]=true;
queue.add(s);
while (queue.size() != 0)
{
s = queue.poll();
Iterator<Integer> i = adj.get(s).listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}
}