Given a boolean matrix grid of size n x m, find the size of the largest region of connected 1s.
A region is a group of 1s connected horizontally, vertically or diagonally (8-directional connectivity). In other words, a cell is connected to all 8 of its neighboring cells.
Return the number of cells in the largest connected region of 1s. If there are no 1s in the matrix, return 0.
Function Signature
def largest_region(grid: list[list[int]]) -> int:
Rules
-
grid
is a list of
n
rows, each a list of
m
integers equal to
0
or
1
.
-
Two
1
cells are in the same region when a chain of
1
cells links them, where each step moves to one of the 8 neighbors (sharing an edge or a corner).
-
Only cells inside the grid are neighbors. Opposite edges of the grid do not wrap around.
Constraints
-
1 <= n, m <= 500
-
grid[i][j]
is either
0
or
1
Examples
Input: grid = [[1,1,0,0],[0,1,1,0],[0,0,1,0],[1,0,0,1]]
Output: 6
The cells (0,0), (0,1), (1,1), (1,2), (2,2) and (3,3) form one region. Most links share an edge, and (2,2) reaches (3,3) through a corner. The cell (3,0) has no 1 among its neighbors, so it is a separate region of size 1.
Input: grid = [[0,0,1,1],[0,0,1,0],[0,1,1,0],[0,1,0,0]]
Output: 6
All six 1s are linked through their neighbors, so they form a single region of size 6.
Input: grid = [[1,0,1],[0,1,0],[1,0,1]]
Output: 5
No two 1s share an edge, but the center touches all four corners diagonally, so the five cells form one region. With only horizontal and vertical connections the answer would be 1.