forked from golumall/Graph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoot_Of_Tree_Give_Min_Height.java
More file actions
94 lines (93 loc) · 1.56 KB
/
Root_Of_Tree_Give_Min_Height.java
File metadata and controls
94 lines (93 loc) · 1.56 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
import java.util.Scanner;
import java.util.Queue;
import java.util.LinkedList;
class Root_Of_Tree_Give_Min_Height
{
int v,min=Integer.MAX_VALUE;
LinkedList<Integer> adj[];
Root_Of_Tree_Give_Min_Height(int v)
{
this.v=v;
adj=new LinkedList[v];
for(int i=1;i<v;i++)
{
adj[i]=new LinkedList<>();
}
}
void addEdge(int src,int dest)
{
adj[src].add(dest);
adj[dest].add(src);
}
void height()
{
boolean visited[]=new boolean[v];
Queue<Integer> q1=new LinkedList<>();
Queue<Integer> q2=new LinkedList<>();
for(int i=1;i<v;i++)
{
q1.add(i);
visited[i]=true;
int h=-1,f=0;
while(!q1.isEmpty()||!q2.isEmpty())
{
while(!q1.isEmpty())
{
f=1;
int p=q1.poll();
for(Integer j:adj[p])
{
if(!visited[j])
{
visited[j]=true;
q2.add(j);
}
}
}
if(f==1)
{
h++;
f=0;
}
while(!q2.isEmpty())
{
f=1;
int p=q2.poll();
for(Integer j:adj[p])
{
if(!visited[j])
{
visited[j]=true;
q1.add(j);
}
}
}
if(f==1)
{
h++;
f=0;
}
}
if(h<min)
min=h;
for(int j=1;j<v;j++)
{
visited[j]=false;
}
}
System.out.println(min);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int v=sc.nextInt();
int e=sc.nextInt();
Root_Of_Tree_Give_Min_Height g=new Root_Of_Tree_Give_Min_Height(v+1);
for(int i=1;i<=e;i++)
{
int src=sc.nextInt();
int dest=sc.nextInt();
g.addEdge(src,dest);
}
g.height();
}
}