A popular problem associated with Leetcode’s online judge. Determine the count of islands in a grid of locations that are either land or water.
Consider the following grid of locations.
Each location is either land (1) or water (0).
Your task is to count the number of islands. An island is surrounded by water and consists of several pieces of land reachable from each other by moving horizontally or vertically. Whatever is outside the four edges of the grid is water.
Input. The input consists of the number of rows of the grid in one line followed by the rows of the grid. For example
The output consists of a single number, the count of islands in the grid. For example, the number of islands in the sample input is 3.
Here is a Ruby implementation.
Want to read more?
I regularly write solutions to programming problems that you may or may not find in technical job interviews. I also love to explain those solutions and answer questions. If you would like to get the latest problem + solution, subscribe to the newsletter or subscribe via RSS. You can also follow me on Twitter, GitHub, and LinkedIn.