Category Archives: RAI

Implementing BFS in Java

In this post, we implement Breadth-First Search (BFS) in Java using an adjacency matrix. BFS is a fundamental graph traversal algorithm that visits all nodes level by level, starting from a source node and exploring all its direct neighbours before moving deeper into the graph. It is widely used in shortest path problems, network analysis, and AI search strategies.

What is BFS?

BFS explores a graph by using a queue data structure. It starts at a chosen node (node 1 in our implementation), adds it to the queue, and then repeatedly dequeues a node, visits all its unvisited neighbours, and enqueues them. This guarantees that all nodes at depth d are visited before any node at depth d+1.

The graph in this implementation is represented as an adjacency matrix — a 2D array where m[i][j] = 1 means there is an edge between node i+1 and node j+1, and 0 means no edge.

Continue reading Implementing BFS in Java