Leetcode 200. Number of Islands
1 min readMar 15, 2021
medium — Apple interview question
Given an m x n
2D binary grid grid
which represents a map of '1'
s (land) and '0'
s (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
Example 2:
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
class Solution {
public:
int maxR{0};
int maxC{0};
vector<vector<bool>> visited;
int dfs(vector<vector<char>>& grid, int r, int c) {
if (r == maxR || r < 0 || c == maxC || c < 0 || visited[r][c] || grid[r][c] == '0') {
return 0;
}
visited[r][c] = true;
dfs(grid, r-1, c);
dfs(grid, r, c+1);
dfs(grid, r, c-1);
dfs(grid, r+1, c);
return 1;
}
int numIslands(vector<vector<char>>& grid) {
int answer = 0;
maxR = grid.size();
maxC = grid[0].size();;
for (int i=0; i<maxR; i++) {
visited.push_back(vector<bool>(maxC, false));
}
for (int r=0; r<maxR; r++) {
for (int c = 0; c<maxC; c++) {
answer += dfs(grid, r, c);
}
}
return answer;
}
};