Problem Statement
Given a 2D array (i.e., a matrix) containing only 1s (land) and 0s (water), count the number of islands in it.
An island is a connected set of 1s (land) and is surrounded by either an edge or 0s (water). Each cell is considered connected to other cells horizontally or vertically (not diagonally).
Example 2
Input: matrix =
![Image](/_next/image?url=https%3A%2F%2Fstorage.googleapis.com%2Fdownload%2Fstorage%2Fv1%2Fb%2Fdesigngurus-prod.appspot.com%2Fo%2FdocImages%252F6388cbb0765bb2154037ce84%252Fimg%3Af03abc-41d-a684-4323-abfbfd8f454.jpg%3Fgeneration%3D1669910293149813%26alt%3Dmedia&w=3840&q=75)
Output: 3
Explanation: The matrix has three islands. See the highlighted cells below.
![Image](/_next/image?url=https%3A%2F%2Fstorage.googleapis.com%2Fdownload%2Fstorage%2Fv1%2Fb%2Fdesigngurus-prod.appspot.com%2Fo%2FdocImages%252F6388cbb0765bb2154037ce84%252Fimg%3Aef81f2a-b31f-8880-fab0-a5fbcf12ca2.jpg%3Fgeneration%3D1669910355602898%26alt%3Dmedia&w=3840&q=75)
Example 1
Input: matrix =
![Image](/_next/image?url=https%3A%2F%2Fstorage.googleapis.com%2Fdownload%2Fstorage%2Fv1%2Fb%2Fdesigngurus-prod.appspot.com%2Fo%2FdocImages%252F6388cbb0765bb2154037ce84%252Fimg%3A5720571-58af-8da3-18c-3b2040ca3e8.jpg%3Fgeneration%3D1669909748924123%26alt%3Dmedia&w=3840&q=75)
Output: 1
Explanation: The matrix has only one island. See the highlighted cells below.
![Image](/_next/image?url=https%3A%2F%2Fstorage.googleapis.com%2Fdownload%2Fstorage%2Fv1%2Fb%2Fdesigngurus-prod.appspot.com%2Fo%2FdocImages%252F6388cbb0765bb2154037ce84%252Fimg%3Aaf4cc62-3d40-e8f1-c68-0e4786ab681.jpg%3Fgeneration%3D1669910244086185%26alt%3Dmedia&w=3840&q=75)
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 300
matrix[i][j] is '0' or '1'.
Try it yourself
Try solving this question here:
Python3
Python3