DFS: Connected Cell in a Grid


Problem Statement :


Consider a matrix where each cell contains either a 0 or a 1 and any cell containing a 1 is called a filled cell. Two cells are said to be connected if they are adjacent to each other horizontally, vertically, or diagonally. In the diagram below, the two colored regions show cells connected to the filled cells. Black on white are not connected.


If one or more filled cells are also connected, they form a region. Note that each cell in a region is connected to at least one other cell in the region but is not necessarily directly connected to all the other cells in the region.


Function Description

Complete the function maxRegion in the editor below. It must return an integer value, the size of the largest region.

maxRegion has the following parameter(s):

grid: a two dimensional array of integers
Input Format

The first line contains an integer, n, the number of rows in the matrix, grid.
The second line contains an integer, m, the number of columns in the matrix.

Each of the following n lines contains a row of m space-separated integers, grid[ i ][ j ].

Constraints


0   <=   n, m <=  10
grid[ i ][ j ] e { 0,1 }


Output Format

Print the number of cells in the largest region in the given matrix.


Sample Input

4
4
1 1 0 0
0 1 1 0
0 0 1 0
1 0 0 0


Sample Output

5



Solution :



title-img


                            Solution in C :

In   C :






#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int max=0,count=1;
int a[]={-1,-1,-1,0,0,1,1,1};
int b[]={-1,0,1,-1,1,-1,0,1};
int safe(int r,int c,int row,int col,int g[][10],int v[][10])
    {
    if(r>=0 && r<row && c>=0 && c<col && g[r][c] && !v[r][c])
        return 1;
    return 0;
}
void dfs(int grid[][10],int visited[][10],int r,int c,int row,int col)
    {
    //int a[]={-1,-1,-1,0,0,1,1,1},i,j;
    //int b[]={-1,0,1,-1,1,-1,0,1};
    int i;
    visited[r][c]=1;
    for(i=0;i<8;i++)
        {
        if(safe(r+a[i],c+b[i],row,col,grid,visited))
        {
            count++;
            dfs(grid,visited,r+a[i],c+b[i],row,col);
            
        }
    }
    if(count>max)
        max=count;
}
int main(){
    int n,visited[10][10],i,j,c=1; 
    scanf("%d",&n);
    int m; 
    scanf("%d",&m);
    int grid[10][10];
    for(int grid_i = 0; grid_i < n; grid_i++){
       for(int grid_j = 0; grid_j < m; grid_j++){
          visited[grid_i][grid_j]=0;
          scanf("%d",&grid[grid_i][grid_j]);
       }
    }
    for(i=0;i<n;i++)
        {
        for(j=0;j<m;j++)
            {
            if(grid[i][j]==1 && !visited[i][j])
            {
                dfs(grid,visited,i,j,n,m);
                count=1;
            }
        }
    }
    /*for(i=0;i<n;i++)
        {
        for(j=0;j<m;j++)
            {
            printf("%d ",visited[i][j]);
        }
        printf("\n");
    }*/
    printf("%d",max);
    return 0;
}
                        


                        Solution in C++ :

In   C++  :





#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;

int count_region(vector<vector<int>> &grid, int i, int j) {
    if (i < 0 || j < 0 || i >= grid.size() || j >= grid[0].size())
        return 0;
    if (grid[i][j] != 1)
        return 0;
    grid[i][j] = 2;
    return 1 + count_region(grid, i + 1, j + 0)
             + count_region(grid, i - 1, j + 0)
             + count_region(grid, i + 0, j + 1)
             + count_region(grid, i + 0, j - 1)
             + count_region(grid, i + 1, j + 1)
             + count_region(grid, i - 1, j - 1)
             + count_region(grid, i + 1, j - 1)
             + count_region(grid, i - 1, j + 1);
}

int get_biggest_region(vector< vector<int> > grid) {
    int res = 0;
    for (int i = 0; i < grid.size(); ++i) {
        for (int j = 0; j < grid[i].size(); ++j) {
            if (grid[i][j] == 1) {
                int size = count_region(grid, i, j);
                res = max(res, size);
            }
        }
    }
    return res;
}

int main(){
    int n;
    cin >> n;
    int m;
    cin >> m;
    vector< vector<int> > grid(n,vector<int>(m));
    for(int grid_i = 0;grid_i < n;grid_i++){
       for(int grid_j = 0;grid_j < m;grid_j++){
          cin >> grid[grid_i][grid_j];
       }
    }
    cout << get_biggest_region(grid) << endl;
    return 0;
}
                    


                        Solution in Java :

In   Java :




import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    
    
    
    public static int getRegion(int[][] matrix, Point pt, int N, int M) {
        // int ptr_x = x;
        // int ptr_y = y;
               
        Stack<Point> stack = new Stack<>();
        ArrayList<Point> visited = new ArrayList<>();
        
        //System.out.printf("Debug: start: x: %d, y : %d\n", pt.x, pt.y);
        stack.push(pt);
        visited.add(pt);
        int area = 1;
        
        while(!stack.isEmpty()) {
            Point popPt = stack.pop();
            if(popPt == null) {
                continue;
            }
            
            /*
            x,y
            x-1,x,y-1,y
            */
            
            Point[] nearby = new Point[] {
                new Point(popPt.x-1, popPt.y-1),
                new Point(popPt.x-1, popPt.y),
                new Point(popPt.x-1, popPt.y+1),
                new Point(popPt.x, popPt.y-1),
                new Point(popPt.x, popPt.y+1),                
                new Point(popPt.x+1, popPt.y-1),
                new Point(popPt.x+1, popPt.y),
                new Point(popPt.x+1, popPt.y+1)
            };
            
            for(Point pt2 : nearby) {
                int x = pt2.x;
                int y = pt2.y;

                if(x < 0 || x >= N || y < 0 || y >= M 
                   || matrix[x][y] == 0
                   || visited.contains(pt2))
                    continue;
                
                //System.out.printf("Debug: x: %d, y: %d, val: %d\n", x, y, matrix[x][y]);
                    

                stack.push(pt2);
                visited.add(pt2);
                area += 1;
            }            
        }
        
        //System.out.printf("Debug:area %d\n", area);
        
        
        return area;
    }
    
    public static int getBiggestRegion(int[][] matrix) {
        int N = matrix.length;
        int M = matrix[0].length;
        
        //System.out.printf("Debug: length: %d, %d\n", N, M);
        
        int maxRegion = 0;
        for(int i = 0; i < N; i += 1) {
            for(int j = 0; j < M; j += 1) {

                if(matrix[i][j] == 1) {
                    //System.out.printf("Debug: %d, %d\n", i, j);
                    int region = getRegion(matrix, new Point(i, j), N, M);
                    //System.out.printf("Debug: %d, %d\n", i, j);
                    if(region > maxRegion)
                        maxRegion = region;
                }
            }
        }
        
        return maxRegion;
    }
    
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int m = in.nextInt();
        int grid[][] = new int[n][m];
        for(int grid_i=0; grid_i < n; grid_i++){
            for(int grid_j=0; grid_j < m; grid_j++){
                grid[grid_i][grid_j] = in.nextInt();
            }
        }
        System.out.println(getBiggestRegion(grid));
    }
}

class Point {
        public int x;
        public int y;
        
    public Point(int a, int b) {
        x =a;
        y = b;
    }
    
        public int hashcode() {
            int hash = 37;
            hash *= x + 17;
            hash *= y + 17;
            return hash;
        }
        
        public boolean equals(Object o) {
            if(o == null)
                return false;
            
            if(o == this)
                return true;
            
            Point o2 = (Point) o;
            return o2.x == this.x && o2.y == this.y;
        }
    }
                    


                        Solution in Python : 
                            
In  Python3 :





def get_biggest_region(grid):
    grid_rows = len(grid)
    grid_cols = len(grid[0])
    # Mark all cells unexplored.
    explored = [[False] * grid_cols for row in range(grid_rows)]
    # Add all cells == 1 to the queue.
    queue = []
    for row in range(grid_rows):
        for col in range(grid_cols):
            if grid[row][col] == 1:
                queue.append((row, col))
    biggest_region = 0
    while len(queue) > 0:
        row, col = queue.pop()
        if explored[row][col]:
            continue
        region_size = get_region_size(grid, row, col, explored)
        biggest_region = max(region_size, biggest_region)
    return biggest_region

def get_region_size(grid, row, col, explored):
    if explored[row][col] or grid[row][col] == 0:
        return 0
    explored[row][col] = True
    size = 1
    for neighbor in get_neighbors(grid, row, col):
        nrow, ncol = neighbor
        size += get_region_size(grid, nrow, ncol, explored)
    return size

def get_neighbors(grid, row, col):
    for nrow in range(row - 1, row + 2):
        for ncol in range(col - 1, col + 2):
            valid_row = nrow >= 0 and nrow < len(grid)
            valid_col = ncol >= 0 and ncol < len(grid[0])
            not_self = nrow != row or ncol != col
            if valid_row and valid_col and not_self:
                yield (nrow, ncol)

n = int(input().strip())
m = int(input().strip())
grid = []
for grid_i in range(n):
    grid_t = list(map(int, input().strip().split(' ')))
    grid.append(grid_t)
print(get_biggest_region(grid))
                    


View More Similar Problems

Tree : Top View

Given a pointer to the root of a binary tree, print the top view of the binary tree. The tree as seen from the top the nodes, is called the top view of the tree. For example : 1 \ 2 \ 5 / \ 3 6 \ 4 Top View : 1 -> 2 -> 5 -> 6 Complete the function topView and print the resulting values on a single line separated by space.

View Solution →

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →