Published
- 2 min read
Breath first search algorithm
Given a graph find paths using breath first traversal
Breath first search alogrithm is used for traversing the graph, its is a also known as level order traversal because it finishes one level if nodes and then moves on to the second level of nodes Most advantageous use of breath first search algorithm is to efficiently find the shortest path b/w two vertices
The “breadth-first search” algorithm, in most cases, can find the shortest path without traversing all paths. This is because when using “breadth-first search”, as soon as a path between the source vertex and target vertex is found, it is guaranteed to be the shortest path between the two nodes.
In Graph theory, the primary use cases of the “breadth-first search” (“BFS”) algorithm are: Traversing all vertices in the “graph”; Finding the shortest path between two vertices in a graph where all edges have equal and positive weights.
graph TD;
A-->C;
A-->E;
C-->D;
C-->A;
D-->C;
D-->B;
B-->E;
B-->D;
E-->A;
E-->B;
/**n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2 */
private void bfsOfAGraph (List<List<Integer>> edges) {
Map<Integer, List<Integer>> adjacencyList = new HashMap<>();
boolean visited[] = new boolean[edges.size()];
//Adjacency list
for (List<Integer> edge : edges) {
if(adjacencyList.get(edge.get(0)) == null) {
ArrayList<Integer> list = new ArrayList<>();
list.add(edge.get(1));
adjacencyList.put(edge.get(0), list);
} else {
List<Integer> list = adjacencyList.get(edge.get(0));
list.add(edge.get(1));
adjacencyList.put(edge.get(0), list);
}
}
Queue<Integer> queue = new LinkedList<>();
adjacencyList.get(0);
queue.add(edges.get(0).get(0));
while (!queue.isEmpty()) {
Integer edge = queue.poll();
if(visited[edge]== true) {
continue;
}
for (Integer neigh : adjacencyList.get(edge)){
queue.add(neigh);
}
visited[edge] = true;
}
//This same algo can be used to find shortest path because its level order traversal and we will find source
//early because we completely search at a level first
}