Number of Islands
Practice this coding question on Coding Gurukul.
Problem statement
A survey drone photographs a rectangular coastline grid. Each cell is land or water, and land belongs to the same island only when connected through shared edges. The survey must count separate islands rather than their area. Your task Count connected components of land cells, where 1 denotes land and 0 denotes water. Connections use the four horizontal and vertical directions. Important details Diagonal contact does not join islands. The entire outer boundary is surrounded by water. Mark visited land so that the same island is not counted repeatedly. A grid containing no land has zero islands. Worked example For rows 110, 010 and 001, the upper-left three land cells form one island. The bottom-right cell touches them only diagonally, making a second island.
Input format
First line: rows columns. Next rows lines: strings of 0 and 1.
Output format
Print the number of islands.
Constraints
1 <= rows, columns <= 300.
Sample input
3 3 110 010 001
Sample output
2
Sign in to run or submit a solution in C++, Java or Python.