Write a program to implement a breadth-first search.
Example 1:
Input: n=6,edges={{1,2},{1,3},{2,4},{4,5},{4,6}}
Output: 1 2 3 4 5 6
Approach:
Java
import java.util.ArrayList;import java.util.LinkedList;import java.util.Queue;public class BreadthFirstSearch {// visited listpublic static ArrayList<Integer> visited = new ArrayList<>();// traversal listpublic static ArrayList<Integer> ans = new ArrayList<>();public static void main(String[] args) {// Adjacency ListsArrayList<ArrayList<Integer>> adj = new ArrayList<>();int v = 7;for (int i = 0; i < v; i++)adj.add(new ArrayList<>());addEdge(adj, 1, 2);addEdge(adj, 1, 3);addEdge(adj, 2, 4);addEdge(adj, 4, 5);addEdge(adj, 4, 6);int source = 1;// bfs callingBFSTraversal(adj, source);// print traversal listans.forEach(i -> System.out.print(i + " "));}/*** @Desc: Method used for BFS* @param graph*/private static void BFSTraversal(ArrayList<ArrayList<Integer>> g, int source) {// create queueQueue<Integer> queue = new LinkedList<>();// add node into queuequeue.add(source);// make visited nodevisited.add(source);// Iterate till queue is not emptywhile (!queue.isEmpty()) {// get front value from queue and pop frontint v = queue.poll();// print the front element of the queueans.add(v);// iterate through the adjacency list// of the popped elementfor (Integer child : g.get(v)) {// If not visitedif (visited.indexOf(child) == -1) {// add element into queuequeue.add(child);// make visitedvisited.add(child);}}}}/*** @Desc : Method used for add edges* @param u* @param v*/private static void addEdge(ArrayList<ArrayList<Integer>> g, int u, int v) {// undirected graphg.get(u).add(v);g.get(v).add(u);}}//Time Complexity: O(n+m)//where n=no of nodes,m=no of edges
C++
#include <bits/stdc++.h>using namespace std;//adjacency listvector<int> adj[1001];//visited array to hold//which node is visit and which//is notbool visited[100001];//function to add the edge//into the adjacency listvoid addEdge(int u,int v){//undirected graphadj[u].push_back(v);adj[v].push_back(u);}void bfsTraversal(int node){//queue to hold the nodesqueue<int> q;q.push(node);//make visited the current nodevisited[node]=1;//iterate till queue is not emptywhile(!q.empty()){//store the front element from queuenode=q.front();//print the front element of the queuecout<<node<<" ";//pop out the first element of the queueq.pop();//iterate through the adjacency list//of the popped elementfor(int child:adj[node]){//if not visited then push into//queue and make it as visitedif(visited[child]==0){q.push(child);visited[child]=1;}}}}int main(){int n=6;int edges=5;addEdge(1,2);addEdge(1,3);addEdge(2,4);addEdge(4,5);addEdge(4,6);int source=1;cout<<"BFS Traversal is ";//call the bfsTraversal function//on source nodebfsTraversal(source);return 0;}//Time Complexity: O(n+m)//where n=no of nodes,m=no of edges
No comments:
Post a Comment