-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathBFS.java
More file actions
64 lines (57 loc) · 1.37 KB
/
Copy pathBFS.java
File metadata and controls
64 lines (57 loc) · 1.37 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
import java.util.*;
import java.io.*;
class BFS
{
private int vertices;
private LinkedList<Integer>adjacency[];
BFS(int v)
{
vertices=v;
adjacency =new LinkedList[v];
for(int i=0;i<v;i++)
{
adjacency[i]=new LinkedList();
}
}
void add_Edge(int v,int w)
{
adjacency[v].add(w);
}
void Traversal(int s)
{
boolean visited[]=new boolean[vertices];
LinkedList<Integer>queue=new LinkedList<Integer>();
visited[s]=true;
queue.add(s);
while(queue.size()!=0)
{
s=queue.poll();
System.out.println(s+" ");
Iterator<Integer>i=adjacency[s].listIterator();
while(i.hasNext())
{
int n = i.next();
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}
public static void main(String[]args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the no. of vertices");
BFS bfs=new BFS(s.nextInt());
System.out.println("Enter the no. of edges");
int n=s.nextInt();
System.out.println("Enter the edges");
for (int i=0;i<n;i++)
{
bfs.add_Edge(s.nextInt(),s.nextInt());
}
System.out.println("enter the vertex from where you want to search");
bfs.Traversal(s.nextInt());
}
}