diff --git a/guide/english/algorithms/graph-algorithms/breadth-first-search/index.md b/guide/english/algorithms/graph-algorithms/breadth-first-search/index.md index 9ca3a467b2..2ad5b92041 100644 --- a/guide/english/algorithms/graph-algorithms/breadth-first-search/index.md +++ b/guide/english/algorithms/graph-algorithms/breadth-first-search/index.md @@ -126,6 +126,60 @@ int main() ``` +### Implementation of BFS in Java +```Java +import java.util.*; +public class BFS { + /* The method takes an adjacency matrix where 1 denotes an edge between i and j. + * n - number of nodes in the graph. + * m - number of edges in the graph. + */ + void Map> createAdjList(int[][] edges, int n, int m) { + Map> adjList = new HashMap>(); + + for (int i = 1; i <= n; i++) { + adjList.put(i, new LinkedList()); + } + + for (int i = 0; i < m; i++) { + List ls = adjList.get(edges[i][0]); + ls.add(edges[i][1]); + ls = adjList.get(edges[i][1]); + ls.add(edges[i][0]); + } + return adjList; + } + /* s - starting node for bfs. + * edges - edge array which stores the edges. + * n - number of nodes in the graph. + * m - number of edges in the graph. + */ + void bfs(int n, int m, int[][] edges, int s) { + // Create an adjacency list from the adjacency matrix edges. + Map> adjList = createAdjList(edges, n, m); + boolean visited[] = new boolean[n+1]; + Queue q = new LinkedList(); + + q.add(s); + visited[s] = true; + System.out.println("BFS traversal of the graph"); + while (!q.isEmpty()) { + int currNode = q.remove(); + Iterator it = adjList.get(currNode).iterator(); + + System.out.println(currNode + "->"); + while (it.hasNext()) { + int neighbor = (Integer)it.next(); + if (visited[neighbor] == false) { + visited[neighbor] = true; + q.add(neighbor); + } + } + } + } +} +``` + #### More Information: