forked from striver79/StriversGraphSeries
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BfsJava
67 lines (59 loc) · 1.97 KB
/
BfsJava
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
import java.lang.*;
import java.io.*;
class GFG
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine().trim());
while(T-->0)
{
String[] s = br.readLine().trim().split(" ");
int V = Integer.parseInt(s[0]);
int E = Integer.parseInt(s[1]);
ArrayList<ArrayList<Integer>>adj = new ArrayList<>();
for(int i = 0; i < V; i++)
adj.add(i, new ArrayList<Integer>());
for(int i = 0; i < E; i++){
String[] S = br.readLine().trim().split(" ");
int u = Integer.parseInt(S[0]);
int v = Integer.parseInt(S[1]);
adj.get(u).add(v);
// adj.get(v).add(u);
}
Solution obj = new Solution();
ArrayList<Integer>ans = obj.bfsOfGraph(V, adj);
for (int i =0 ;i < ans.size (); i++)
System.out.print (ans.get (i) + " ");
System.out.println();
}
}
}
// } Driver Code Ends
class Solution
{
public ArrayList<Integer> bfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj)
{
ArrayList<Integer> bfs = new ArrayList<>();
boolean vis[] = new boolean[V];
Queue<Integer> q = new LinkedList<>();
q.add(0);
vis[0] = true;
while (!q.isEmpty())
{
Integer node = q.poll();
bfs.add(node);
// Get all adjacent vertices of the dequeued vertex s
// If a adjacent has not been visited, then mark it
// visited and enqueue it
for(Integer it: adj.get(node)) {
if(vis[it] == false) {
vis[it] = true;
q.add(it);
}
}
}
return bfs;
// Code here
}
}