-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathGraph.java
More file actions
91 lines (75 loc) · 1.78 KB
/
Graph.java
File metadata and controls
91 lines (75 loc) · 1.78 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
// Java program to count all paths from a source
// to a destination.
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
// This class represents a directed graph using
// adjacency list representation
class Graph {
// No. of vertices
private int V;
// Array of lists for
// Adjacency List
// Representation
private LinkedList<Integer> adj[];
@SuppressWarnings("unchecked")
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList<>();
}
// Method to add an edge into the graph
void addEdge(int v, int w)
{
// Add w to v's list.
adj[v].add(w);
}
// A recursive method to count
// all paths from 'u' to 'd'.
int countPathsUtil(int u, int d,
int pathCount)
{
// If current vertex is same as
// destination, then increment count
if (u == d) {
pathCount++;
}
// Recur for all the vertices
// adjacent to this vertex
else {
Iterator<Integer> i = adj[u].listIterator();
while (i.hasNext()) {
int n = i.next();
pathCount = countPathsUtil(n, d, pathCount);
}
}
return pathCount;
}
// Returns count of
// paths from 's' to 'd'
int countPaths(int s, int d)
{
// Call the recursive method
// to count all paths
int pathCount = 0;
pathCount = countPathsUtil(s, d,
pathCount);
return pathCount;
}
// Driver Code
public static void main(String args[])
{
Graph g = new Graph(5);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(0, 3);
g.addEdge(1, 3);
g.addEdge(2, 3);
g.addEdge(1, 4);
g.addEdge(2, 4);
int s = 0, d = 3;
System.out.println(g.countPaths(s, d));
}
}