You're given a 2D grid of characters representing a map of '1's (land) and '0's (water). An island is formed by connecting adjacent lands horizontally or vertically. Your task is to count how many islands exist in the grid.
The key challenge is ensuring that each island is only counted once, even though it may span multiple grid cells. To handle this, we will use a depth-first search (DFS) traversal to "sink" or mark visited cells so we don’t count them again.
The grid can be traversed cell by cell. Whenever we find a cell with '1', we recognize it as the start of a new island. We then initiate a DFS from that cell to traverse the rest of the island and mark all of its land cells as visited (for example, by changing '1' to '0').
The DFS explores all four directions (up, down, left, right). If we stay within bounds and find a land cell, we continue the DFS from that point. This continues recursively until the entire island is marked.
By doing this for every unvisited '1' we encounter, we ensure each island is counted exactly once.
- An empty grid (0 rows or 0 columns) should return 0.
- A grid full of '0's has no islands and also returns 0.
- A grid with all '1's and no '0's will return 1, as the entire grid is one large island.
Time Complexity: O(m × n), where m is the number of rows and n is the number of columns in the grid. Each cell is visited once.
Space Complexity: O(m × n) in the worst case due to the recursion stack in DFS if the entire grid is filled with land.
This problem is a classic use case for graph traversal in 2D space. The DFS-based strategy is both intuitive and effective for marking and counting islands. It ensures no part of an island is double-counted, and handles complex shapes and placements of land in the grid seamlessly.