Skip to content

Commit 105f2cd

Browse files
committed
Added Breath First Search Algorithm
1 parent c3408c7 commit 105f2cd

File tree

2 files changed

+245
-0
lines changed

2 files changed

+245
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import java.util.*;
2+
3+
4+
public class BreathFirstSearch {
5+
// Graph adjacency list
6+
private List<List<Integer>> adjList;
7+
8+
//BFS class constructor to the adjacency list
9+
public BreathFirstSearch(int numVertices){
10+
adjList = new ArrayList<>();
11+
for (int i = 0; i < numVertices; i++){
12+
adjList.add(new ArrayList<>());
13+
}
14+
}
15+
16+
//Add edge to the graph
17+
public void addEdge(int from, int to){
18+
adjList.get(from).add(to);
19+
adjList.get(to).add(from); // This makes the graph undirected
20+
}
21+
22+
//Iterative BFS for a given starting point
23+
public void bfsIterative(int start){
24+
boolean[] visited = new boolean[adjList.size()];
25+
Queue<Integer> queue = new LinkedList<>();
26+
27+
visited[start] = true;
28+
queue.add(start);
29+
30+
System.out.println("Iterative: ");
31+
while(!queue.isEmpty()){
32+
int vertex = queue.poll();
33+
System.out.print(vertex + " ");
34+
35+
//Traverse all adjacent vertices
36+
for (int adj : adjList.get(vertex)){
37+
if (!visited[adj]) {
38+
visited[adj] = true;
39+
queue.add(adj);
40+
}
41+
}
42+
}
43+
}
44+
45+
//Recursive BFS for a given starting point
46+
public void bfsRecursive(int start){
47+
boolean[] visited = new boolean[adjList.size()];
48+
Queue<Integer> queue = new LinkedList<>();
49+
queue.add(start);
50+
51+
System.out.println("Recursive: ");
52+
bfsRecursiveUtil(queue, visited);
53+
}
54+
55+
//Auxiliar method to perform BFS recursively
56+
private void bfsRecursiveUtil(Queue<Integer> queue, boolean[] visited){
57+
//Base case: stop if the queue is empty
58+
if (queue.isEmpty()) {
59+
return;
60+
}
61+
int vertex = queue.poll();
62+
63+
//Not visited yet case
64+
if (!visited[vertex]) {
65+
visited[vertex] = true;
66+
System.out.print(vertex + " ");
67+
68+
//Enqueue all unvisited adjacent vertices
69+
for (int adj : adjList.get(vertex)){
70+
if (!visited[adj]) {
71+
queue.add(adj);
72+
}
73+
}
74+
}
75+
//Recursive call
76+
bfsRecursiveAux(queue, visited);
77+
}
78+
79+
//Main method to demonstrate BFS
80+
public static void main(String[] args) {
81+
BreathFirstSearch graph = new BreathFirstSearch(6);
82+
83+
//Adding edges to the graph
84+
graph.addEdge(0, 1);
85+
graph.addEdge(1, 3);
86+
graph.addEdge(1, 4);
87+
graph.addEdge(2, 5);
88+
89+
//Perform both BFS approaches
90+
graph.bfsIterative(0);
91+
System.out.println("");
92+
graph.bfsRecursive(0);
93+
}
94+
95+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
# Overview of the Depth First Search (DFS) Code in Java 💻
2+
3+
## What's Happening in the Code? ❓
4+
The provided Java code implements Breath First Search (BFS), a fundamental graph traversal algorithm. Let's walk through the details!
5+
6+
### 1. **Setting Up the Graph** 📝
7+
We start by creating a graph structure using an **adjacency list**, represented by a `List` of `List<Integer>`. Each index in the main list corresponds to a vertex, and each sublist contains its neighboring vertices. This makes it easy to keep track of which nodes are connected.
8+
9+
```java
10+
private List<List<Integer>> adjList;
11+
```
12+
13+
### 2. **Constructing the Graph** ⚙️
14+
The `BreathFirstSearch` constructor initializes the adjacency list with `numVertices` empty lists:
15+
16+
```java
17+
public BreathFirstSearch(int numVertices){
18+
adjList = new ArrayList<>();
19+
for (int i = 0; i < numVertices; i++){
20+
adjList.add(new ArrayList<>());
21+
}
22+
}
23+
```
24+
25+
### 3. **Adding Edges**
26+
The `addEdge` method links two vertices, `from` and `to`, by adding each to the other's adjacency list:
27+
28+
```java
29+
public void addEdge(int from, int to){
30+
adjList.get(from).add(to);
31+
adjList.get(to).add(from);
32+
}
33+
```
34+
35+
This makes it an **undirected graph**, where the connection between nodes goes both ways.
36+
37+
### 4. **The BFS Iterative Method** ↪️
38+
The `bfsIteratice` method sets up an array called `visited` to keep track of which nodes have been visited during the traversal,
39+
as well setting up a `queue` to process the vertices level by level:
40+
41+
```java
42+
public void bfsIterative(int start){
43+
boolean[] visited = new boolean[adjList.size()];
44+
Queue<Integer> queue = new LinkedList<>();
45+
46+
visited[start] = true;
47+
queue.add(start);
48+
49+
System.out.println("Iterative: ");
50+
while(!queue.isEmpty()){
51+
int vertex = queue.poll();
52+
System.out.print(vertex + " ");
53+
54+
//Traverse all adjacent vertices
55+
for (int adj : adjList.get(vertex)){
56+
if (!visited[adj]) {
57+
visited[adj] = true;
58+
queue.add(adj);
59+
}
60+
}
61+
}
62+
}
63+
```
64+
65+
### 5. **The BFS Recursive Method** 🔄
66+
The main `bfsRecursive` method sets up an array called `visited` to keep track of which nodes have been visited during the traversal,
67+
as well setting up a `queue` to process the vertices level by level then, it calls the util function:
68+
69+
```java
70+
public void bfsRecursive(int start){
71+
boolean[] visited = new boolean[adjList.size()];
72+
Queue<Integer> queue = new LinkedList<>();
73+
queue.add(start);
74+
75+
System.out.println("Recursive: ");
76+
bfsRecursiveUtil(queue, visited);
77+
}
78+
```
79+
80+
### 6. **BFS Utility Method** ❤️
81+
The `bfsRecursiveUtil` method is the heart of the algorithm. It recursively visits nodes, prints and dequeues them as it goes:
82+
83+
```java
84+
private void bfsRecursiveUtil(Queue<Integer> queue, boolean[] visited){
85+
//Base case: stop if the queue is empty
86+
if (queue.isEmpty()) {
87+
return;
88+
}
89+
int vertex = queue.poll();
90+
91+
//Not visited yet case
92+
if (!visited[vertex]) {
93+
visited[vertex] = true;
94+
System.out.print(vertex + " ");
95+
96+
//Enqueue all unvisited adjacent vertices
97+
for (int adj : adjList.get(vertex)){
98+
if (!visited[adj]) {
99+
queue.add(adj);
100+
}
101+
}
102+
}
103+
//Recursive call
104+
bfsRecursiveAux(queue, visited);
105+
}
106+
```
107+
- **Visit**: The current node is marked as visited and printed.
108+
- **Recur**: For each unvisited neighbor, `bfsUtil` is called recursively.
109+
110+
### 6. **Main Method** 💪
111+
Finally, the `main` method demonstrates the DBFS by building a sample graph and starting the traversal from vertex `0`:
112+
113+
```java
114+
public static void main(String[] args) {
115+
BreathFirstSearch graph = new BreathFirstSearch(6);
116+
117+
//Adding edges to the graph
118+
graph.addEdge(0, 1);
119+
graph.addEdge(1, 3);
120+
graph.addEdge(1, 4);
121+
graph.addEdge(2, 5);
122+
123+
//Perform both BFS approaches
124+
graph.bfsIterative(0);
125+
System.out.println("");
126+
graph.bfsRecursive(0);
127+
}
128+
```
129+
130+
## What Happens When You Run It? ⏳
131+
1. The graph is created with 6 vertices.
132+
2. Edges are added between the vertices to form connections.
133+
3. BFS starts from vertex `0` and traverses reachable vertices layer by layer.
134+
135+
### Example Output: ✅
136+
If you run the code, you might see an output like:
137+
```
138+
Depth First Search starting from vertex 0:
139+
0 1 3 4
140+
```
141+
This output shows the order in which the vertices are visited during the BFS traversal.
142+
143+
## Fun Fact: 🧐
144+
DFS is great for finding the shortest path in unweighted graphs, which is very useful for GPS Navigation systems.
145+
146+
147+
And that’s how BFS works in Java!
148+
149+
### Created by
150+
David Bernal based on the job done by Nkeiruka Whenu

0 commit comments

Comments
 (0)