Bfs Example
Bfs Example
Core Concepts
1. Graph Representation
Your code uses an adjacency list to represent the graph:
java
For vertex "s" connected to "r" and "w", the list would be ["r", "w"]
2. Vertex Properties
Each vertex tracks important information during BFS:
java
Step 1: Initialization
java
What happens: All vertices start as WHITE (undiscovered) with infinite distance.
java
What happens: The source vertex is marked as discovered (GRAY) and added to the queue.
while (!queue.isEmpty()) {
Vertex u = queue.poll(); // Take next vertex from queue
What happens:
3. For each WHITE neighbor: mark it GRAY, set distance, set parent, add to queue
Graph Structure:
Initial State:
Queue: [r, w]
Queue: [w, v]
Queue: [v, t, x]
And so on...
1. Distance Calculation
java
v.distance = u.distance + 1;
This ensures shortest path distances because BFS explores level by level.
2. Path Reconstruction
java
v.predecessor = u;
By storing predecessors, you can trace back the shortest path from any vertex to the source.
3. Avoiding Cycles
java
if (v.color.equals("WHITE")) {
Algorithm Properties
Time Complexity: O(V + E)
V = number of vertices
E = number of edges
Output Interpretation
Your printResult() method shows:
Vertex d prev
s 0 nil
r 1 s
w 1 s
v 2 r
t 2 w
x 2 w
u 3 t
y 3 x
Your code is a textbook implementation that correctly demonstrates all these BFS principles!