Skip to content

Commit 4763be9

Browse files
committed
Breadth First Search Algorithm in Java
1 parent 8374edc commit 4763be9

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Diff for: BreadthFirstSearch/Java/BFS.java

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
* Time-Complexity:- O(V+E)
3+
*
4+
*/
5+
6+
7+
import java.util.*;
8+
9+
public class BFS {
10+
11+
static ArrayList<ArrayList<Integer>> graph;
12+
static Queue<Integer> queue;
13+
public static void traverse(int source)
14+
{
15+
queue = new LinkedList<>();
16+
queue.add(source);
17+
boolean[] visited = new boolean[graph.size()];
18+
visited[source]=true;
19+
while(!queue.isEmpty())
20+
{
21+
int q = queue.poll();
22+
System.out.println(q);
23+
ArrayList<Integer> list = graph.get(q);
24+
for(int i=0;i<list.size();i++)
25+
{
26+
if(!visited[list.get(i)])
27+
{
28+
queue.add(list.get(i));
29+
visited[list.get(i)] = true;
30+
}
31+
}
32+
}
33+
}
34+
public static void main(String[] args) {
35+
// TODO Auto-generated method stub
36+
graph = new ArrayList<>();
37+
Scanner sc = new Scanner(System.in);
38+
int vertices = sc.nextInt();
39+
int edges = sc.nextInt();
40+
for(int i=0;i<vertices;i++)
41+
graph.add(new ArrayList<>());
42+
for(int i=0;i<edges;i++)
43+
{
44+
int u = sc.nextInt();
45+
int v = sc.nextInt();
46+
graph.get(u-1).add(v-1);
47+
graph.get(v-1).add(u-1);
48+
}
49+
int source = sc.nextInt();
50+
traverse(source-1);
51+
sc.close();
52+
}
53+
}

0 commit comments

Comments
 (0)