Leetcode 200. Number of Islands
Given a 2D grid map of ‘1’s (land) and ‘0’s (water), count 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.
300x300
for such problems in coding interviews.#include <vector>
#include <queue>
class Solution {
public:
int numIslands(std::vector<std::vector<char>>& grid) {
if (grid.empty() || grid[0].empty()) {
return 0;
}
int num_islands = 0;
int rows = grid.size();
int cols = grid[0].size();
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < cols; ++c) {
if (grid[r][c] == '1') {
// Found an island, start a BFS/DFS
num_islands++;
fill(grid, r, c);
}
}
}
return num_islands;
}
private:
void fill(std::vector<std::vector<char>>& grid, int r, int c) {
int rows = grid.size();
int cols = grid[0].size();
std::queue<std::pair<int, int>> q;
q.push({r, c});
grid[r][c] = '0'; // mark as visited
std::vector<std::pair<int, int>> directions = \{\{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
while (!q.empty()) {
auto [cur_r, cur_c] = q.front();
q.pop();
for (auto [dr, dc] : directions) {
int new_r = cur_r + dr;
int new_c = cur_c + dc;
if (new_r >= 0 && new_r < rows && new_c >= 0 && new_c < cols && grid[new_r][new_c] == '1') {
q.push({new_r, new_c});
grid[new_r][new_c] = '0'; // mark as visited
}
}
}
}
};
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?