Number of islands II

Given a matrix of integers A of size N x M consisting of 0 and 1.
A group of connected 1’s forms an island. From a cell (i, j) such that A[i][j] = 1
you can visit any cell that shares a side with (i, j) and value in that cell is 1.

More formally, from any cell (i, j) if A[i][j] = 1 you can visit:

  1. (i-1, j) if (i-1, j) is inside the matrix and A[i-1][j] = 1.

  2. (i, j-1) if (i, j-1) is inside the matrix and A[i][j-1] = 1.

  3. (i+1, j) if (i+1, j) is inside the matrix and A[i+1][j] = 1.

  4. (i, j+1) if (i, j+1) is inside the matrix and A[i][j+1] = 1.

Return the number of islands.

Note:

  1. Rows are numbered from top to bottom and columns are numbered from left to right.

  2. Your solution will run on multiple test cases. If you are using global variables, make sure to clear them.



Input Format

The only argument given is the integer matrix A.

Output Format

Return the number of islands.

Constraints

1 <= N, M <= 100
0 <= A[i] <= 1

For Example

Input 1:
    A = [   [0, 1, 0]
            [0, 0, 1]
            [1, 0, 0]   ]
Output 1:
    3

Input 2:
      A = [ [1, 1, 0, 0, 0]
            [1, 1, 0, 0, 0]
            [0, 0, 1, 0, 0]
            [0, 0, 0, 1, 1]    ]
Output 2:
    3
NOTE: You only need to implement the given function. Do not read input, instead use the arguments to the function. Do not print the output, instead return values as specified. Still have a doubt? Checkout Sample Codes for more details.
Start solving Number of islands II on Interview Code Editor
Sign Up
to access hints and editorial solutions for Number of islands II

Discussion


Loading...
Click here to start solving coding interview questions