-
Notifications
You must be signed in to change notification settings - Fork 0
/
BFSTraversal.java
69 lines (60 loc) · 2.06 KB
/
BFSTraversal.java
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
package com.datastructures.GraphTraversal;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class BFSTraversal {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int node = sc.nextInt(); //no.of nodes
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
//for 1 base indexing i.e starting vertex from 1 to V
for(int i = 0; i <= node; i )
{
ans.add(new ArrayList<>());
}
int edges = sc.nextInt(); //no. of edges
//making graphs by joining vertices with edges
for(int i = 1; i <= edges; i )
{
System.out.println("Enter u and v");
int u = sc.nextInt();
int v = sc.nextInt();
ans.get(u).add(v);
ans.get(v).add(u);
}
//bfs
ArrayList<Integer> print = new ArrayList<>();
//V 1 for 1 based indexing nodes---> nodes start from 1 to V not 0 to V-1
boolean[] bool = new boolean[node 1];
//using loop inorder to check every node is traversed using bfs or not
//helpful for unconnected graph
for(int i = 1; i <= node; i )
{
//check if current node is visited or not
if(!bool[i])
{
Queue<Integer> q = new LinkedList<>();
q.add(i);
bool[i] = true;
while(!q.isEmpty())
{
//take out node from queue and mark it as visited
int nd = q.poll();
print.add(nd);
//traverse neighbour nodes of curr nodes
for(Integer neighbour : ans.get(node))
{
if(!bool[neighbour])
{
q.add(neighbour);
bool[neighbour] = true;
}
}
}
}
}
System.out.println(print);
}
}