200. 岛屿数量
给你一个由 '1'
(陆地)和 '0'
(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 1:
输入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1
示例 2:
输入:grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
输出:3
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j]
的值为'0'
或'1'
BFS
class Solution {
public:
// 方向
const int dx[4] = {0, 0, 1, -1};
const int dy[4] = {-1, 1, 0, 0};
int numIslands(vector<vector<char>>& grid) {
int sum = 0, n = grid.size(), m = grid[0].size();
// 遍历所有格子
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (grid[i][j] != '0') {
++sum;
bfs(grid, i, j);
}
}
}
return sum;
}
void bfs(vector<vector<char>>& grid, int x, int y) {
queue<pair<int, int>> pointQueue;
// 推入队列同时标记true
pointQueue.push({x, y});
grid[x][y] = '0';
while (!pointQueue.empty()) {
// 获取队首元素
auto cur = pointQueue.front(); pointQueue.pop();
// 队首元素的横坐标和纵坐标
int curx = cur.first, cury = cur.second;
// 遍历四个方向
for (int i = 0; i < 4; ++i) {
int mx = curx + dx[i], my = cury + dy[i];
// 越界直接跳过
if (mx < 0 || mx >= grid.size() || my < 0 || my >= grid[0].size()) continue;
// 不越界,判断格子是否能走
if (grid[mx][my] != '0') {
// 推入队列同时标记true
pointQueue.push({mx, my});
grid[mx][my] = '0';
}
}
}
}
};
class Solution {
private:
const int dx[4] = {0, 0, 1, -1};
const int dy[4] = {1, -1, 0, 0};
public:
int numIslands(vector<vector<char>>& grid) {
// 初始化注意先n后m,n行m列
int ans = 0, n = grid.size(), m = grid[0].size();
// Lambda函数写法
auto bfs = [&](int x, int y) {
queue<pair<int, int>> Q;
grid[x][y] = '0';
Q.push({x, y});//Q.push(make_pair(x, y));queue<int> q q.push(x);
while(!Q.empty()) {
auto k = Q.front();
Q.pop();
for(int i = 0; i < 4; ++i) {
int nx = k.first + dx[i], ny = k.second + dy[i];
if(nx >= 0 && nx < n && ny >= 0 && ny < m && grid[nx][ny] == '1') {
grid[nx][ny] = '0';
// 注意emplace和push的区别
Q.emplace(nx, ny);//queue<tuple<int, string, int> q.emplace(1, "2njfef", 2342);
}
}
}
};
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) {
if(grid[i][j] == '1') {
++ans;
bfs(i, j);
}
}
}
return ans;
}
};
DFS
class Solution {
public:
const int dx[4] = {-1, 0, 0, 1};
const int dy[4] = {0, 1, -1, 0};
int numIslands(vector<vector<char>>& grid) {
int sum = 0, m = grid.size(), n = grid[0].size();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] != '0') {
dfs(grid, i, j);
++sum;
}
}
}
return sum;
}
void dfs(vector<vector<char>>& grid, int x, int y) {
if (grid[x][y] == '1') {
grid[x][y] = '0';
for (int i = 0; i < 4; ++i) {
int mx = x + dx[i], my = y + dy[i];
if (mx >= 0 && mx < grid.size() && my >= 0 && my < grid[0].size()) {
dfs(grid, mx, my);
}
}
}
}
};