logo CodeStepByStep logo

countIslands

Language/Type: C++ Grid traversals
Related Links:

Write a function named countIslands that accepts a reference to a Grid of integers as a parameter, where every integer in the grid is either 0 to represent water or 1 to represent land, and returns an integer count of how many contiguous "islands" of land are in the grid. An "island" is a connected group of land areas (1) that neighbor each other directly up, down, east, or west (not diagonal). For example, suppose the grid contains the following values:

Grid<int> map {
    {0, 0, 0, 0, 0, 0, 1},
    {0, 1, 1, 1, 0, 0, 0},
    {0, 0, 0, 1, 0, 0, 0},
    {0, 1, 0, 1, 0, 1, 0},
    {0, 0, 0, 0, 0, 1, 0},
    {0, 1, 1, 0, 0, 1, 0},
    {0, 1, 1, 0, 0, 0, 0}
};

There are five distinct islands in this grid, so the call of countIslands(map) should return 5.

Your code should work for a board of any size, even one with 0 rows or columns. You may assume that no values appear in the grid other than 0 and 1.

Function: Write a C++ function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.