Connected Cells in a Grid

Consider a matrix where each cell contains either a 0 or a 1. Any cell containing a  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 following grid, all cells marked X are connected to the cell marked Y.
If one or more filled cells are also connected, they form a region. Note that each cell in a region is connected to zero or more cells in the region but is not necessarily directly connected to all the other cells in the region.
Given an nXm matrix, find and print the number of cells in the largest region in the matrix. Note that there may be more than one region in the matrix.

Example:

Input:  n=3,m=3, grid[][]={{1,1,0},{1,0,0},{0,0,1}}
Output: 3

Approach

C++

#include <bits/stdc++.h>
using namespace std;
int grid[100][100];
int dx[] = {-1, -101110, -1};
int dy[] = {01110, -1, -1, -1};
int nm;
int cnt;
int vis[100][100];
bool isValid(int xint y)
{
    if (x < 0 || x >= n || y < 0 || y >= m)
        return false;
    if (vis[x][y] == 1 || grid[x][y] == 0)
        return false;
    return true;
}
void dfs(int xint y)
{
    vis[x][y] = 1;
    cnt++;
    for (int i = 0i < 8i++)
    {
        if (isValid(x + dx[i], y + dy[i]))
            dfs(x + dx[i], y + dy[i]);
    }
}
int main()
{
    n = 3m = 3;
    grid[0][0] = 1grid[0][1] = 1grid[0][2] = 0;
    grid[1][0] = 1grid[1][1] = 0grid[1][2] = 0;
    grid[2][0] = 0grid[2][1] = 0grid[2][2] = 1;
    for (int i = 0i < ni++)
    {
        for (int j = 0j < mj++)
        {
            vis[i][j] = 0;
        }
    }
    int ans = INT_MIN;
    for (int i = 0i < ni++)
    {
        for (int j = 0j < mj++)
        {

            if (vis[i][j] == 0 && grid[i][j] == 1)
            {
                cnt = 0;
                dfs(ij);
                ans = max(anscnt);
            }
        }
    }
    cout << ans << "\n";
    return 0;
}


No comments:

Post a Comment