-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathShortestPathBetween2nodes.java
More file actions
102 lines (88 loc) · 2 KB
/
ShortestPathBetween2nodes.java
File metadata and controls
102 lines (88 loc) · 2 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
92
93
94
95
96
97
98
99
100
101
102
// Java representation of finding shortest
// distance between node i and j
import java.util.*;
class GFG
{
// prints the path between node i and node j
static void ShortestPath(int i, int j, int k, int m,
int n)
{
// path1 stores path of node i to lca and
// path2 stores path of node j to lca
Vector<Integer> path1=new Vector<Integer>(),
path2=new Vector<Integer>();
int x = m - 1;
// push node i in path1
path1.add(i);
// keep pushing parent of node labelled
// as i to path1 until lca is reached
while (x != k)
{
path1.add(i / 2);
i = i / 2;
x--;
}
int y = n - 1;
// push node j to path2
path2.add(j);
// keep pushing parent of node j till
// lca is reached
while (y != k)
{
path2.add(j / 2);
j = j / 2;
y--;
}
// printing path from node i to lca
for (int l = 0; l < path1.size(); l++)
System.out.print( path1.get(l) + " ");
// printing path from lca to node j
for (int l = path2.size() - 2; l >= 0; l--)
System.out.print( path2.get(l) + " ");
System.out.println();
}
// returns the shortest distance between
// nodes labelled as i and j
static int ShortestDistance(int i, int j)
{
// vector to store binary form of i and j
Vector<Integer> v1=new Vector<Integer>(),
v2=new Vector<Integer>();
// finding binary form of i and j
int p1 = i;
int p2 = j;
while (i != 0)
{
v1.add(i % 2);
i = i / 2;
}
while (j != 0)
{
v2.add(j % 2);
j = j / 2;
}
// as binary form will be in reverse order
// reverse the vectors
Collections.reverse(v1);
Collections.reverse(v2);
// finding the k that is lca (i, j)
int m = v1.size(), n = v2.size(), k = 0;
if (m < n)
{
while (k < m && v1.get(k) == v2.get(k))
k++;
}
else
{
while (k < n && v1.get(k) == v2.get(k))
k++;
}
ShortestPath(p1, p2, k - 1, m, n);
return m + n - 2 * k;
}
public static void main(String args[])
{
System.out.println( ShortestDistance(1, 2) );
System.out.println(ShortestDistance(4, 3) );
}
}