Leetcode 200: Number of Islands

grid47
grid47
Exploring patterns and algorithms
Oct 18, 2024 7 min read

A map of glowing islands floating gently, with the number of islands appearing as a soft count.
Solution to LeetCode 200: Number of Islands Problem

You are given a 2D grid representing a map, where ‘1’ represents land and ‘0’ represents water. Your task is to count how many islands are formed by connecting adjacent lands horizontally or vertically. An island is a collection of ‘1’s connected either horizontally or vertically.
Problem
Approach
Steps
Complexity
Input: The input consists of an m x n grid of '1's (land) and '0's (water). The grid is represented as a list of lists where each inner list corresponds to a row in the grid.
Example: grid = [ ['1','1','1','1','0'], ['1','1','0','1','0'], ['1','1','0','0','0'], ['0','0','0','0','0'] ]
Constraints:
• The grid will have between 1 and 300 rows and 1 and 300 columns.
• Each cell of the grid is either '0' or '1'.
Output: Return the number of islands formed in the given grid, where each island consists of connected '1's.
Example: Output: 1
Constraints:
• The output should be an integer representing the number of islands.
Goal: The goal is to count how many distinct islands are present in the grid by connecting adjacent '1's.
Steps:
• Iterate through each cell in the grid.
• When a '1' is encountered, it means the start of a new island. Increment the island count.
• Use Depth First Search (DFS) to mark all connected '1's as visited by changing them to '0'. This ensures that the same island is not counted multiple times.
• Continue until all cells have been processed.
Goal: The grid will always contain at least one row and one column, and each element in the grid is either '0' or '1'.
Steps:
• 1 <= m, n <= 300
• grid[i][j] is either '0' or '1'.
Assumptions:
• The grid is well-formed, with each row containing the same number of columns.
Input: grid = [ ['1','1','0','0','0'], ['1','1','0','0','0'], ['0','0','1','0','0'], ['0','0','0','1','1'] ]
Explanation: In this example, there are three distinct islands. The first island consists of the first two rows of '1's, the second island is formed by the '1' at position (2,2), and the third island is the '1' at position (3,3). The output is 3.

Input: grid = [ ['1','1','1','1','0'], ['1','1','0','1','0'], ['1','1','0','0','0'], ['0','0','0','0','0'] ]
Explanation: This grid forms a single island that spans multiple rows and columns. The entire set of '1's is connected horizontally and vertically. The output is 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus