Design a Data Structure to Represent a Terrain of Islands in a Sea

Difficulty: EASYCategory: LLDFrequency: 1Asked On 2025-01-20

Problem Statement

Design and implement a data structure that models a 2D terrain made up of islands and water. Each island is represented by a coordinate (x, y) on a grid, while all other coordinates are considered water by default.

The system should support adding islands, removing them, querying island connectivity, and finding groups of connected islands (archipelagos).

🎯 Functional Requirements

Implement the following core operations:

1. addIsland(int x, int y)

•Marks coordinate (x, y) as an island.

2. removeIsland(int x, int y)

•Removes the island at coordinate (x, y) and turns it into water.

3. isIsland(int x, int y) → boolean

•Returns true if the coordinate is currently an island.

4. areConnected(int x1, int y1, int x2, int y2) → boolean

•Returns true if the two given islands are part of the same connected component (archipelago), i.e., they are connected through adjacent islands (4-directional or 8-directional — specify).

5. countIslands() → int

•Returns the total number of distinct islands (connected components).


Solution

Comments