Unlock the Pattern
Given a 2D binary matrix of size m x n where each cell contains either a 1 or 0, find how many cells in the matrix can reach to any other cell with the same value by an uninterrupted vertical or horizontal line.
[ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 1, 0, 1 ] ]
Explanation. Each `1` can only reach itself since they are not adjacent to another `1`. Similarly, each `0` is isolated.
[ [ 1, 1, 0 ], [ 1, 1, 0 ], [ 0, 0, 1 ] ]
Explanation. The four `1`s can all reach each other while the two '0's can reach each other.
[ [ 0, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 0 ] ]
Explanation. All of the `0`s are contiguous and can connect, and the single `1` can only reach itself.
Follow-up: Could you solve this problem using a breadth-first search (BFS) approach or union-find to optimize the search operation?
The matrix will have dimensions `1 <= m, n <= 100`. Each of the matrix entries is either `0` or `1`.
- Views
- 2