Login and get codingYou are tasked with counting the amount of islands in a 2D matrix / grid.
Islands are represented by 1s, oceans by 0. If the 1s are connected either horizontally or vertically (not diagonally), then they count as one island. You can assume a grid has a limited size up to 10x10. Try to make the search / count of number of islands as efficient as possible. If no islands are found, just return 0.
The goal is to find how many islands there are in the ocean, regardless of its size.
Examples:
###### Example 1 grid = [[1, 1, 0, 0, 1], [1, 1, 0, 0, 1], [0, 1, 0, 0, 0], [1, 0, 0, 0, 1], [1, 0, 0, 0, 0]] expected: 4 islands (top left island has size 5; top right = 2, bottom left = 2, bottom right = 1) ###### Example 2 grid = [[1, 0, 0, 1], [1, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 1]] expected: 6 islands (only top left one has size 2, all other islands are of size 1) ###### Example 3 empty = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] expected = 0 islandsTasks:
- Complete
count_islands
which returns the number of islands found.- Complete
mark_islands
which marks all visited islands in-place (modifying the passed-in grid directly), no return value.
187 out of 193 users completed this Bite.
Will you be the 188th person to crack this Bite?
Resolution time: ~80 min. (avg. submissions of 5-240 min.)
Our community rates this Bite 7.0 on a 1-10 difficulty scale.
» Up for a challenge? 💪