# 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 :

```                            ```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[],int v[])
{
if(r>=0 && r<row && c>=0 && c<col && g[r][c] && !v[r][c])
return 1;
return 0;
}
void dfs(int grid[],int visited[],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,i,j,c=1;
scanf("%d",&n);
int m;
scanf("%d",&m);
int grid;
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.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);
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);
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.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)
# 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)
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))```
```

## Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

## Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

## Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

## Balanced Forest

Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a

## Jenny's Subtrees

Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .

## Tree Coordinates

We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For