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

Reverse a doubly linked list

This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.

View Solution →

Tree: Preorder Traversal

Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's

View Solution →

Tree: Postorder Traversal

Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the

View Solution →

Tree: Inorder Traversal

In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your $inOrder* func

View Solution →

Tree: Height of a Binary Tree

The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For example, the following binary tree is of height : image Function Description Complete the getHeight or height function in the editor. It must return the height of a binary tree as an integer. getHeight or height has the following parameter(s): root: a reference to the root of a binary

View Solution →

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 →