</>CodexBash
Back to problems
Not started

Count the islands

Medium
2000 ms limit256 MB memoryGraphsMatrices

Stuck?

Show a hint

Walk every cell. On unvisited land, add one and flood the whole island, marking each cell as you arrive so nothing is counted twice.

Next in this lesson

Course schedule

A grid of 1 for land and 0 for water. An island is land joined together up, down, left or right. Diagonals do not connect. Count the islands.

Worked example#

1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 1

Three islands: the two by two block at the top left, the single cell in the middle, and the pair at the bottom right.

The bottom right pair is one island, not two, because the cells sit side by side. The middle cell touches nothing, so it is its own island.

The idea#

A grid is a graph. Each cell is a vertex and each cell is joined to the neighbour above, below, left and right. Counting islands is counting connected pieces, which is a walk with a visited set.

Walk the grid cell by cell. When you meet land you have not visited, that is a new island, so add one and then walk the whole island, marking every cell as visited so it is never counted again.

for each cell:
    if it is land and not visited:
        islands += 1
        flood the whole island, marking as you go

The flood can be depth first or breadth first. Either works, because the question is what is connected, not how far away it is.

Marking visited#

The simplest way is to change each visited land cell to water as you go. It needs no extra memory, and after the first pass nothing revisits it.

If the caller must not see the grid changed, keep a separate visited grid instead. Worth knowing which one the problem wants, because quietly destroying the input is a real bug in real code.

Mark a cell visited as you arrive, not when you finish with it. Otherwise the same cell is queued several times over before any of them is processed.

Watch the recursion depth#

A grid that is all land, of any size, becomes one recursion as deep as there are cells. Fifty thousand cells is a stack overflow in most languages. Breadth first with an explicit queue has no such limit.

The cost#

Time O(rows x cols): every cell is visited once. Memory O(rows x cols) in the worst case, for the stack or the queue.

Constraints#

  • 1 <= rows, cols <= 300
  • Every cell is 0 or 1, written as rows of digits with no spaces

Input

grid is a row count then that many rows, each a run of 0 and 1 with no spaces.

Output

The number of islands.

Examples

Input

4
11000
11000
00100
00011

Output

3

The block at the top left, the single cell, and the pair at the bottom right.

Input

2
11111
11111

Output

1

All land joined together is one island.

Input

2
000
000

Output

0

No land at all.

Something wrong with this problem? Report an issue

Ready to try it

Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.

Free, and it stays free. No card.