Write a program to implement the depth-first search on a 2D grid.
Example 1:
Input: grid[][3]={{1,2,3},{4,5,6},{7,8,9}}
Output: 1 2 3 6 9 8 5 4 7
Approach:
Java
public class DFS2DGrid {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("DFS traversal of 2d grid is");dfs2Dgrid(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 dfs2Dgrid(int x, int y, int n, int m, int[][] grid) {// make the current cell as visitedvisited[x][y] = 1;// print the current nodeSystem.out.print(grid[x][y] + " ");// iterate for all the// directionsfor (int i = 0; i < 4; i++) {int newx = dx[i] + x;int newy = dy[i] + y;// if valid and not visitedif (newx >= 0 && newx < n && newy >= 0 && newy < m && visited[newx][newy] == 0) {// call dfs functiondfs2Dgrid(newx, newy, n, m, grid);}}}}
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//dfs traversal on 2d gridvoid dfs2Dgrid(int x,int y,int n,int m,int grid[][3]){//mark the current cell//as visitedvisited[x][y]=1;//print the current node datacout<<grid[x][y]<<" ";//iterate for all the//directionsfor(int i=0;i<4;i++){//new xint newx=dx[i]+x;//new yint newy=dy[i]+y;//if valid and not visitedif(newx>=0&&newx<n&&newy>=0&&newy<m&&visited[newx][newy]==0){//call dfs functiondfs2Dgrid(newx,newy,n,m,grid);}}}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<<"DFS traversal of 2d grid is\n";dfs2Dgrid(0,0,n,m,grid);return 0;}
No comments:
Post a Comment