Write a program to implement a breadth-first search on a 2D grid.
Example 1:
Input: grid[][3]={{1,2,3},{4,5,6},{7,8,9}}
Output: 1 2 4 3 5 7 6 8 9
Approach:
Java
import java.util.LinkedList;import java.util.Queue;import javafx.util.Pair;public class BFS2DGrid {static int visited[][] = null;public static void main(String[] args) {// 2d grid inputint grid[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };// dimensions of the gridint n = 3, m = 3;visited = new int[3][3];System.out.println("BFS traversal of 2d grid is");bfs2Dgrid(0, 0, n, m, grid);}// direction up,right,down,leftstatic int dx[] = { -1, 0, 1, 0 };static int dy[] = { 0, 1, 0, -1 };// method to find the dfs traversal on 2d gridprivate static void bfs2Dgrid(int x, int y, int n,int m, int[][] grid) {// queue pair to store the coordinates of the cellQueue<Pair<Integer, Integer>> queue =new LinkedList<Pair<Integer, Integer>>();// mark the current cell as visitedvisited[x][y] = 1;// push the current cell into the queuequeue.add(new Pair<Integer, Integer>(x, y));// iterate till queue is not emptywhile (!queue.isEmpty()) {Pair<Integer, Integer> p = queue.poll();// current xx = p.getKey();y = p.getValue();// print the current cell dataSystem.out.print(grid[x][y] + " ");// iterate for all the directionsfor (int i = 0; i < 4; i++) {// new xint newx = x + dx[i];// new yint newy = y + dy[i];// if cell is valid and not visitedif (newx >= 0 && newx < n && newy >= 0 && newy < m&& visited[newx][newy] == 0) {// push into the queuequeue.add(new Pair(newx, newy));// mark as visitedvisited[newx][newy] = 1;}}}}}
C++
#include <bits/stdc++.h>using namespace std;//store the visted nodeint visited[1001][1001];//direction up,right,down,leftint dx[4]={-1,0,1,0};int dy[4]={0,1,0,-1};//function to find the//bfs traversal of 2d gridvoid bfs2Dgrid(int x,int y,int n,int m,int grid[][3]){//queue pair to store the//coordinates of the cellqueue<pair<int,int>> q;//mark the current cell//as visitedvisited[x][y]=1;//push the current cell into//the queueq.push({x,y});//iterate till queue//is not emptywhile(!q.empty()){//current xx=q.front().first;//current yy=q.front().second;//print the current cell datacout<<grid[x][y]<<" ";//pop the first element from the//queueq.pop();//iterate for all//the directionsfor(int i=0;i<4;i++){//new xint newx=x+dx[i];//new yint newy=y+dy[i];//if cell is valid and not vistedif(newx>=0&&newx<n&&newy>=0&&newy<m&&visited[newx][newy]==0){//push into the queueq.push({newx,newy});//mark as visitedvisited[newx][newy]=1;}}}}int main(){//2d grid inputint grid[][3]={{1,2,3},{4,5,6},{7,8,9}};//dimensions of the gridint n=3,m=3;cout<<"BFS traversal of 2d grid is\n";bfs2Dgrid(0,0,n,m,grid);return 0;}
No comments:
Post a Comment