Given an N × M grid of characters, where '0' represents water and '1' represents land, return the number of islands.
An island is a group of land cells connected horizontally, vertically, or diagonally. Two land cells that touch at a corner belong to the same island.
Example 1
Input:
grid = [
['1', '1', '1', '0', '1'],
['1', '0', '0', '0', '0'],
['1', '1', '1', '0', '1'],
['0', '0', '0', '1', '1']
]Output: 2
Explanation: The land at (0, 4) is isolated. The diagonal move from (2, 2) to (3, 3) joins the land on the left to the land in the lower-right corner, forming the other island. Coordinates are zero-indexed.
Example 2
Input:
grid = [
['1', '0', '0', '0', '1'],
['0', '1', '0', '1', '0'],
['0', '0', '1', '0', '0'],
['0', '1', '0', '1', '0']
]Output: 1
Explanation: The center cell (2, 2) connects diagonally to four land cells. Two of those cells lead to the top corners, so all seven land cells form one island.
Approach
An island consists of land cells connected horizontally, vertically, or diagonally. When we find a land cell, use breadth-first search (BFS) to visit all land cells connected to it. This marks the entire island before the grid scan continues, so we count it only once.
In Example 1, a search starting at (0, 0) can reach (2, 4) through the diagonal connection from (2, 2) to (3, 3). These cells belong to the same island even though they appear far apart in a row-by-row scan.
BFS uses a queue to store land cells whose neighbors still need to be checked. Remove one cell at a time and examine all eight neighboring positions. If a neighbor is unvisited land, mark it visited and add it to the queue. Marking it immediately prevents multiple cells from adding the same neighbor.
When the queue becomes empty, every cell in the current island has been visited. Continue scanning the grid. Any land cell that is still unvisited belongs to another island, so increase the count and start BFS again.
Algorithm
Initialise a
visitedgrid withfalseat every position and set the island count to0.Scan the grid row by row. Whenever you find an unvisited
'1', increment the island count, mark the cell visited, and add it to a BFS queue.Remove the front cell from the queue. Try row and column offsets from
-1through1to find its neighbors.Skip the offset pair
(0, 0)because it refers to the current cell. The remaining eight pairs cover horizontal, vertical, and diagonal moves.For each neighbor, first check that its position is within the grid. If it is land and has not been visited, mark it visited and add it to the queue.
Repeat until the queue is empty, then resume scanning the grid for another unvisited land cell.
Return the island count after checking every cell.
Dry Run
Number of islands
Solution
#include <bits/stdc++.h>using namespace std;class Solution {private: // Mark every land cell reachable using horizontal, vertical, or diagonal moves. void bfs(int startRow, int startCol, const vector<vector<char>>& grid, vector<vector<bool>>& visited) { const int rows = grid.size(); const int cols = grid[0].size(); // Each queue entry holds a land cell whose neighbors are pending. queue<pair<int, int>> cells; // Mark the starting cell before adding it to the queue. visited[startRow][startCol] = true; cells.push({startRow, startCol}); while (!cells.empty()) { // Take the next cell and explore its neighbors. auto [row, col] = cells.front(); cells.pop(); // Combining these offsets covers all eight neighboring positions. for (int dr = -1; dr <= 1; ++dr) { for (int dc = -1; dc <= 1; ++dc) { // Zero movement points back to the current cell. if (dr == 0 && dc == 0) { continue; } int nextRow = row + dr; int nextCol = col + dc; // Check bounds before indexing either grid. if (nextRow < 0 || nextRow >= rows || nextCol < 0 || nextCol >= cols) { continue; } // Only unvisited land cells can extend this island. if (grid[nextRow][nextCol] == '1' && !visited[nextRow][nextCol]) { // Mark now to prevent duplicate queue entries. visited[nextRow][nextCol] = true; cells.push({nextRow, nextCol}); } } } } // An empty queue means the entire island has been visited. }public: // Count islands by starting BFS from each unvisited land cell. int numIslands(vector<vector<char>>& grid) { // An empty grid contains no islands. if (grid.empty() || grid[0].empty()) { return 0; } const int rows = grid.size(); const int cols = grid[0].size(); // Keep visited flags across all BFS calls to avoid counting land twice. vector<vector<bool>> visited(rows, vector<bool>(cols, false)); int islands = 0; // Scan every position to find islands that BFS has not reached. for (int row = 0; row < rows; ++row) { for (int col = 0; col < cols; ++col) { if (grid[row][col] == '1' && !visited[row][col]) { // Count this island and mark all its connected land cells. ++islands; bfs(row, col, grid, visited); } } } return islands; }};int main() { // '1' represents land, and '0' represents water. vector<vector<char>> grid = { {'1', '1', '1', '0', '1'}, {'1', '0', '0', '0', '0'}, {'1', '1', '1', '0', '1'}, {'0', '0', '0', '1', '1'} }; Solution solution; // Diagonal connections are included when counting the islands. cout << solution.numIslands(grid) << '\n'; // Prints 2. return 0;}Complexity Analysis
Time Complexity: O(N × M). The outer scan checks every cell. Across all BFS runs, each land cell enters the queue once and has at most eight neighbors checked.
Space Complexity: O(N × M). The visited grid stores one flag per cell, and the queue uses at most O(N × M) space.
Interview follow-up Questions
Two neighboring cells might reach the same land cell before it gets its turn in the queue. Marking it when it is added ensures it is queued only once.
Be the first to add a comment.