Given a grid representing a map with land and water, the task is to determine the number of distinct landmasses. This problem tests graph traversal skills, a fundamental concept in algorithm design and software engineering.
Imagine you have a digital elevation map represented as a two-dimensional array. Each cell in the array represents a location, and its value indicates whether it's part of a connected land area (represented by 1) or water (represented by 0). Your goal is to write a function that calculates the total number of separate, non-overlapping land regions in this map. Land regions are considered connected if they are adjacent either horizontally or vertically (not diagonally).
The brute-force approach would be like trying to count the number of distinct groups of friends at a party by going up to each person individually and asking if they're part of a group we haven't seen before. For each cell, you'd check its neighbors to see if they're land and part of a previously counted landmass. This involves iterating through the entire grid multiple times. The time complexity is O(mn(number of islands)), where m and n are the dimensions of the grid, and the space complexity is O(1) as it doesn't use extra space.
Work through this problem with AI coaching and get real-time feedback
Practice This Problem