forked from thuva4/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.java
More file actions
53 lines (49 loc) · 1.06 KB
/
BFS.java
File metadata and controls
53 lines (49 loc) · 1.06 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
/*
* Time-Complexity:- O(V+E)
*
*/
import java.util.*;
public class BFS {
static ArrayList<ArrayList<Integer>> graph;
static Queue<Integer> queue;
public static void traverse(int source)
{
queue = new LinkedList<>();
queue.add(source);
boolean[] visited = new boolean[graph.size()];
visited[source]=true;
while(!queue.isEmpty())
{
int q = queue.poll();
System.out.println(q);
ArrayList<Integer> list = graph.get(q);
for(int i=0;i<list.size();i++)
{
if(!visited[list.get(i)])
{
queue.add(list.get(i));
visited[list.get(i)] = true;
}
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
graph = new ArrayList<>();
Scanner sc = new Scanner(System.in);
int vertices = sc.nextInt();
int edges = sc.nextInt();
for(int i=0;i<vertices;i++)
graph.add(new ArrayList<>());
for(int i=0;i<edges;i++)
{
int u = sc.nextInt();
int v = sc.nextInt();
graph.get(u-1).add(v-1);
graph.get(v-1).add(u-1);
}
int source = sc.nextInt();
traverse(source-1);
sc.close();
}
}