// C Program to find area of the largest region of 1s #include <stdio.h> #include <stdlib.h> // Define constants for rows and columns #define ROWS 5 #define COLS 7 // A function to check if cell(r, c) can be included in DFS int isSafe(int M[ROWS][COLS], int r, int c, int rows, int cols) { // Row number is in range, column number is in range, // and value is 1 return (r >= 0 && r < rows) && (c >= 0 && c < cols) && (M[r][c] == 1); } // Depth-First-Search to visit all cells in the current island void DFS(int M[ROWS][COLS], int r, int c, int rows, int cols, int *area) { // These arrays are used to get row and column numbers of 8 // neighbours of a given cell int dirR[] = {-1, -1, -1, 0, 0, 1, 1, 1}; int dirC[] = {-1, 0, 1, -1, 1, -1, 0, 1}; // Increment area of region by 1 (*area)++; // Mark this cell as visited M[r][c] = 0; // Recur for all connected neighbours for (int i = 0; i < 8; i++) { int newR = r + dirR[i]; int newC = c + dirC[i]; if (isSafe(M, newR, newC, rows, cols)) { DFS(M, newR, newC, rows, cols, area); } } } // Function to find area of the largest region of 1s int largestRegion(int M[ROWS][COLS], int rows, int cols) { // Initialize result as 0 and traverse through // all cells of given matrix int maxArea = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { // If a cell with value 1 is found if (M[i][j] == 1) { int area = 0; DFS(M, i, j, rows, cols, &area); // Maximize the area if (area > maxArea) { maxArea = area; } } } } return maxArea; } int main() { int M[ROWS][COLS] = { {1, 0, 0, 0, 1, 0, 0}, {0, 1, 0, 0, 1, 1, 1}, {1, 1, 0, 0, 0, 0, 0}, {1, 0, 0, 1, 1, 0, 0}, {1, 0, 0, 1, 0, 1, 1} }; printf("%d\n", largestRegion(M, ROWS, COLS)); return 0; }