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

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →

AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

View Solution →

Waiter

You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →