Largest Component in Three Rows
Problem statement
You are given a binary matrix matrix with exactly three rows and n columns. A component is a maximal group of cells containing 1 connected through horizontal or vertical neighbors.
Return the number of cells in the largest component, or 0 when there are no ones. Diagonal contact does not connect cells.
Your final solution must run in O(n) time using O(1) auxiliary space. The supplied matrix is excluded from the auxiliary-space count.
Function
largestThreeRowComponent(matrix: int[][]) → intExamples
Example 1
matrix = [[1,1,1],[0,0,1],[1,1,1]]return = 7The final column joins the upper and lower runs into one component of seven cells.
Example 2
matrix = [[1,1,1],[1,0,1],[1,1,1]]return = 8The middle column separates the frontier into two tails of the same earlier component. Rejoining them must count the old cells only once.
Example 3
matrix = [[0,0],[0,0],[0,0]]return = 0Components contain only ones, so an all-zero matrix returns 0.
Constraints
matrix.length == 3.1 <= n <= 100000, and every row has lengthn.- Every cell is
0or1.