Loading...
You are given a two-dimensional integer array matrix of 0s and 1s.
1 represents land.0 represents water.An island is a maximal group of 1 cells connected horizontally or vertically. Note that neighbors can only be directly horizontal or vertical, not diagonal.
Return the number of islands in matrix.
Input: matrix = [[1,1,0,0,0],[1,1,0,0,1],[0,0,0,1,1],[0,0,0,0,0]]
Output: 2
Explanation: The four 1s in the top-left corner form one island. The 1 at row 1, column 4 connects
down to the two 1s in row 2, forming a second island. No 1 in one island is 4-directionally
adjacent to a 1 in the other.
Input: matrix = [[1,0],[0,1]]
Output: 2
Explanation: The two 1s only touch at a corner, which does not count as connected, so they form
two separate islands of size 1 each.
Input: matrix = [[0,0,0],[0,0,0]]
Output: 0
Explanation: There is no land at all, so there are no islands.
n = matrix.lengthm = matrix[0].lengthn, m ≤100matrix[i][j] is either 0 or 1.Click "Run" to test with sample cases or "Submit" to run all tests.