Write a program to find the connected components in a 2D grid.
Example 1:
Input: grid[][4]={{1,1,0,0},{0,1,0,0},{1,0,0,1},{1,1,0,1}}
Output: 3
Approach: Using Depth First Search (DFS).
Java
public class DFSConnectedComponent2D {static int visited[][] = null;public static void main(String[] args) {// input as 2d grid 1 means include in// component 0 means not include in componentint grid[][] = { { 1, 1, 0, 0 }, { 0, 1, 0, 0 },{ 1, 0, 0, 1 }, { 1, 1, 0, 1 } };// dimensions of the gridint n = 4, m = 4;// varibale to hold the connected// componentsint connected_components = 0;visited = new int[n][n];for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {// if grid[i][j]==1 and it is not visited// run 2d dfs on itif (grid[i][j] == 1 && visited[i][j] == 0) {// increment the connected// componentsconnected_components++;// call the dfsdfs2Dgrid(i, j, n, m, grid);}}}System.out.println("No of connnected components are "+ connected_components);}// direction up,right,down,leftstatic int dx[] = { -1, 0, 1, 0 };static int dy[] = { 0, 1, 0, -1 };// funtion to check the// validation of the cellpublic static boolean isValid(int x, int y, int n,int m, int grid[][]) {// if cell is out of boundary// return falseif (x < 0 || x >= n || y < 0 || y >= m)return false;// if the cell is alredy visited or// it is not grid[x][y]==0// return falseif (visited[x][y] == 1 || grid[x][y] == 0)return false;// else return truereturn true;}// 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;// 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 (isValid(newx, newy, n, m, grid)) {// call dfs functiondfs2Dgrid(newx, newy, n, m, grid);}}}}
C++
#include <bits/stdc++.h>using namespace std;//visted to hold the visited cellint visited[1001][1001];//all four directionsint dx[4]={-1,0,1,0};int dy[4]={0,1,0,-1};//funtion to check the//validation of the cellbool isValid(int x,int y,int n,int m,int grid[][4]){//if cell is out of boundary//return falseif(x<0||x>=n||y<0||y>=m)return false;//if the cell is alredy visited or//it is not grid[x][y]==0//return falseif(visited[x][y]==1||grid[x][y]==0)return false;//else return truereturn true;}void dfs2Dgrid(int x,int y,int n,int m,int grid[][4]){//mark the current cell as visitedvisited[x][y]=1;//iterate for all the directionsfor(int i=0;i<4;i++){//new xint newx=x+dx[i];//new yint newy=y+dy[i];//if the new cell is validif(isValid(newx,newy,n,m,grid)){//run dfs on itdfs2Dgrid(newx,newy,n,m,grid);}}}int main(){//input as 2d grid 1 means include in//component 0 means not inlcude in componentint grid[][4]={{1,1,0,0},{0,1,0,0},{1,0,0,1},{1,1,0,1}};//dimensions of the gridint n=4,m=4;//varibale to hold the connected//componentsint connected_components=0;for(int i=0;i<n;i++){for(int j=0;j<m;j++){//if grid[i][j]==1 and it is not visited//run 2d dfs on itif(grid[i][j]==1&&visited[i][j]==0){//increment the connected//componentsconnected_components++;//call the dfsdfs2Dgrid(i,j,n,m,grid);}}}cout<<"No of connnected components are\n";cout<<connected_components<<"\n";return 0;}
Approach 2: Using Breadth-First Search (BFS).
Java
import java.util.LinkedList;import java.util.Queue;import javafx.util.Pair;public class BFSConnectedComponent2D {static int visited[][] = null;public static void main(String[] args) {// input as 2d grid 1 means include in// component 0 means not include in componentint grid[][] = { { 1, 1, 0, 0 }, { 0, 1, 0, 0 },{ 1, 0, 0, 1 }, { 1, 1, 0, 1 } };// dimensions of the gridint n = 4, m = 4;// varibale to hold the connected componentsint connected_components = 0;visited = new int[n][n];for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {// if grid[i][j]==1 and it is not visited// run 2d bfs on itif (grid[i][j] == 1 && visited[i][j] == 0) {// increment the connected// componentsconnected_components++;// call the dfsbfs2Dgrid(i, j, n, m, grid);}}}System.out.println("No of connnected components are "+ connected_components);}// direction up,right,down,leftstatic int dx[] = { -1, 0, 1, 0 };static int dy[] = { 0, 1, 0, -1 };// funtion to check the// validation of the cellpublic static boolean isValid(int x, int y,int n, int m, int grid[][]) {// if cell is out of boundary// return falseif (x < 0 || x >= n || y < 0 || y >= m)return false;// if the cell is alredy visited or// it is not grid[x][y]==0// return falseif (visited[x][y] == 1 || grid[x][y] == 0)return false;// else return truereturn true;}// 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();// 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 (isValid(newx, newy, n, m, grid)) {// push into the queuequeue.add(new Pair(newx, newy));// mark as visitedvisited[newx][newy] = 1;}}}}}
C++
#include <bits/stdc++.h>using namespace std;//visted to hold the visited cellint visited[1001][1001];//all four directionsint dx[4]={-1,0,1,0};int dy[4]={0,1,0,-1};//funtion to check the//validation of the cellbool isValid(int x,int y,int n,int m,int grid[][4]){//if cell is out of boundary//return falseif(x<0||x>=n||y<0||y>=m)return false;//if the cell is alredy visited or//it is not grid[x][y]==0//return falseif(visited[x][y]==1||grid[x][y]==0)return false;//else return truereturn true;}//bfs on the 2d gridvoid bfs2Dgrid(int x,int y,int n,int m,int grid[][4]){//queue to hold the cellqueue<pair<int,int>> q;//marks the current cell as visitedvisited[x][y]=1;//push the current cell into//the queueq.push({x,y});//iterate till the queue is//not emptywhile(!q.empty()){//current xx=q.front().first;//current yy=q.front().second;//popped out 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];//check if cell is valid or notif(isValid(newx,newy,n,m,grid)){//push the current cell into//the queueq.push({newx,newy});//marks the current cell as//visitedvisited[newx][newy]=1;}}}}int main(){//input as 2d grid 1 means include in//component 0 means not inlcude in componentint grid[][4]={{1,1,0,0},{0,1,0,0},{1,0,0,1},{1,1,0,1}};//dimensions of the gridint n=4,m=4;//varibale to hold the connected//componentsint connected_components=0;for(int i=0;i<n;i++){for(int j=0;j<m;j++){//if grid[i][j]==1 and it is not visited//run 2d dfs on itif(grid[i][j]==1&&visited[i][j]==0){//increment the connected//componentsconnected_components++;//call the dfsbfs2Dgrid(i,j,n,m,grid);}}}cout<<"No of connnected components are\n";cout<<connected_components<<"\n";return 0;}
No comments:
Post a Comment