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.
Examples
Example 1
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.
Example 2
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.
Example 3
Input: matrix = [[0,0,0],[0,0,0]]
Output: 0
Explanation: There is no land at all, so there are no islands.
Constraints
n=matrix.length
m=matrix[0].length
1≤n, m≤100
matrix[i][j] is either 0 or 1.
Loading editor...
Log in to run your code. Your draft is saved in this browser.Log inSign up