This approach uses Depth-First Search (DFS) to explore the grid. We iterate over each cell in the grid, and every time we find an unvisited '1', it indicates the discovery of a new island. We then perform DFS from that cell to mark all the connected '1's as visited, effectively marking the entire island.
Time Complexity: O(m*n) where m is the number of rows and n is the number of columns since each cell is visited once.
Space Complexity: O(m*n) in the worst case due to the recursion stack used by DFS.
1class Solution:
2 def dfs(self, grid, r, c):
3 if r < 0 or c < 0 or r >= len(grid) or c >= len(grid[0]) or grid[r][c] == '0':
4 return
5 grid[r][c] = '0'
6 self.dfs(grid, r-1, c)
7 self.dfs(grid, r+1, c)
8 self.dfs(grid, r, c-1)
9 self.dfs(grid, r, c+1)
10
11 def numIslands(self, grid):
12 if not grid:
13 return 0
14 num_islands = 0
15 for r in range(len(grid)):
16 for c in range(len(grid[0])):
17 if grid[r][c] == '1':
18 num_islands += 1
19 self.dfs(grid, r, c)
20 return num_islands
Python's solution uses a method dfs
to explore and mark connected lands. We iterate over the entire grid, and for every '1' encountered, initiate a DFS from that position, effectively exploring the whole island.
This approach uses Breadth-First Search (BFS) to traverse the grid. Similar to DFS, we treat each '1' as a node in a graph. On encountering a '1', we initiate a BFS to explore all connected '1's (island nodes) by utilizing a queue for the frontier, marking them in-place as visited.
Time Complexity: O(m*n), where m and n are rows and columns.#
Space Complexity: O(min(m, n)) due to the queue storage in BFS.
1#include <vector>
2#include <queue>
3using namespace std;
4
5void bfs(vector<vector<char>>& grid, int r, int c) {
6 queue<pair<int, int>> q;
7 q.push({r, c});
8 grid[r][c] = '0';
9 vector<vector<int>> directions {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
10 while (!q.empty()) {
11 int cr = q.front().first;
12 int cc = q.front().second;
13 q.pop();
14 for (vector<int>& dir : directions) {
15 int nr = cr + dir[0], nc = cc + dir[1];
16 if (nr >= 0 && nr < grid.size() && nc >= 0 && nc < grid[0].size() && grid[nr][nc] == '1') {
17 grid[nr][nc] = '0';
18 q.push({nr, nc});
19 }
20 }
21 }
22}
23
24int numIslands(vector<vector<char>>& grid) {
25 int numIslands = 0;
26 for (int i = 0; i < grid.size(); i++) {
27 for (int j = 0; j < grid[i].size(); j++) {
28 if (grid[i][j] == '1') {
29 bfs(grid, i, j);
30 numIslands++;
31 }
32 }
33 }
34 return numIslands;
35}
The C++ solution employs a std::queue
to facilitate BFS over '1's in the grid. When a '1' is encountered, we launch BFS, exploring all connected '1's by marking them and enqueuing adjacent unvisited ones, effectively dedicating BFS for the whole discovered island.