-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFSShortSearch.java
More file actions
108 lines (96 loc) · 2.85 KB
/
BFSShortSearch.java
File metadata and controls
108 lines (96 loc) · 2.85 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
103
104
105
106
107
108
package graph;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
public class BFSShortSearch {
int[] distance;
boolean[] visited;
Graph g;
class Graph{
int V;
ArrayList<Integer>[] adj;
Graph(int V){
this.V=V;
adj=new ArrayList[V+1];
}
public void addEdge(int src,int dest){
if(adj[src]==null){
ArrayList<Integer> al = new ArrayList();
al.add(dest);
adj[src]=al;
}
else{
adj[src].add(dest);
}
if(adj[dest]==null){
ArrayList<Integer> al = new ArrayList();
al.add(src);
adj[dest]=al;
}
else{
adj[dest].add(src);
}
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int q=sc.nextInt();
BFSShortSearch sol=new BFSShortSearch();
for(int i=0;i<q;i++){
int nodes=sc.nextInt();
int edges=sc.nextInt();
sol.initialize(nodes,edges);
for(int j=0;j<edges;j++){
int src=sc.nextInt();
int dest = sc.nextInt();
sol.g.addEdge(src,dest);
}
int source = sc.nextInt();
sol.bfs(source);
sol.printDistance();
}
}
void initialize(int nodes,int edges){
g= new Graph(nodes);
distance=new int[nodes+1];
visited= new boolean[nodes+1];
for(int i=1;i<=nodes;i++){
distance[i]=-1;
}
}
void bfs(int source){
distance[source]=0;
LinkedList<Integer> queue=new LinkedList();
queue.add(source);
visited[source]=true;
while(!queue.isEmpty()){
int node = queue.poll();
if(g.adj[node]!=null){
Iterator<Integer> itr = g.adj[node].iterator();
while(itr.hasNext()){
int neighbor = itr.next();
if(!visited[neighbor]){
queue.add(neighbor);
distance[neighbor]=distance[node]+1;
visited[neighbor]=true;
}
}
}
}
}
void printDistance(){
int len = distance.length;
StringBuilder sb = new StringBuilder();
for(int i=1;i<len;i++){
if(distance[i]==0)
continue;
if(distance[i]!=-1){
sb.append(distance[i]*6+" ");
continue;
}
sb.append(distance[i]+" ");
}
System.out.println(sb.toString().substring(0,sb.length()-1));
}
}