forked from Py-Contributors/AlgorithmsAndDataStructure
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1 from pojith/pojith-patch-1
Create Breadth-First Search (BFS) Searching.java
- Loading branch information
Showing
1 changed file
with
71 additions
and
0 deletions.
There are no files selected for viewing
71 changes: 71 additions & 0 deletions
71
Java/Algorithm/SearchingAlgorithm/Breadth-First Search (BFS) Searching .java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
import java.util.*; | ||
|
||
public class BFS { | ||
private int V; // Number of vertices | ||
private LinkedList<Integer> adj[]; // Adjacency list representation of the graph | ||
|
||
public BFS(int v) { | ||
V = v; | ||
adj = new LinkedList[v]; | ||
for (int i = 0; i < v; ++i) | ||
adj[i] = new LinkedList(); | ||
} | ||
|
||
// Function to add an edge into the graph | ||
void addEdge(int v, int w) { | ||
adj[v].add(w); | ||
} | ||
|
||
// BFS traversal starting from a given source vertex | ||
void BFS(int s) { | ||
// Mark all the vertices as not visited | ||
boolean visited[] = new boolean[V]; | ||
|
||
// Create a queue for BFS | ||
LinkedList<Integer> queue = new LinkedList<>(); | ||
|
||
// Mark the current node as visited and enqueue it | ||
visited[s] = true; | ||
queue.add(s); | ||
|
||
while (queue.size() != 0) { | ||
// Dequeue a vertex from the queue and print it | ||
s = queue.poll(); | ||
System.out.print(s + " "); | ||
|
||
// Get all adjacent vertices of the dequeued vertex s. If an adjacent vertex has not been visited, | ||
// then mark it visited and enqueue it | ||
Iterator<Integer> i = adj[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 scanner = new Scanner(System.in); | ||
|
||
System.out.print("Enter the number of vertices: "); | ||
int V = scanner.nextInt(); | ||
|
||
BFS graph = new BFS(V); | ||
|
||
System.out.println("Enter the edges (vertex pairs, -1 to stop): "); | ||
while (true) { | ||
int v1 = scanner.nextInt(); | ||
if (v1 == -1) break; | ||
int v2 = scanner.nextInt(); | ||
graph.addEdge(v1, v2); | ||
} | ||
|
||
System.out.print("Enter the starting vertex for BFS: "); | ||
int startVertex = scanner.nextInt(); | ||
|
||
System.out.println("Breadth First Traversal starting from vertex " + startVertex + ":"); | ||
graph.BFS(startVertex); | ||
} | ||
} |