Number of Islands
MediumGiven an m x n
grid consisting of 1
s (land) and 0
s (water), return the number of islands. An island is formed by connecting adjacent 1
s vertically or horizontally.
Example:
Input: grid = [ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ] Output: 3 Explanation: - The first island consists of the top-left 1s. - The second island consists of the middle 1. - The third island consists of the bottom-right 1s. Input: grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] Output: 1 Explanation: There is only one connected island.
Test Cases
Test Cases
Input
6 1 1 1 0 0 0 1 1 1 1 0 0 1 1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
Expected Output
2
Step 1
Step 2
Step 3
Step 4
Step 1: Identify the Pattern
Number of Islands
MediumGiven an m x n
grid consisting of 1
s (land) and 0
s (water), return the number of islands. An island is formed by connecting adjacent 1
s vertically or horizontally.
Example:
Input: grid = [ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ] Output: 3 Explanation: - The first island consists of the top-left 1s. - The second island consists of the middle 1. - The third island consists of the bottom-right 1s. Input: grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] Output: 1 Explanation: There is only one connected island.
Test Cases
Test Cases
Input
6 1 1 1 0 0 0 1 1 1 1 0 0 1 1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
Expected Output
2
Step 1
Step 2
Step 3
Step 4
Step 1: Identify the Pattern