题目
代码(首刷自解)
class Solution {
public:
int ans;
int numIslands(vector<vector<char>>& grid) {
int 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')
continue;
ans++;
dfs(grid, i, j, m, n);
}
}
return ans;
}
void dfs(vector<vector<char>>& grid, int i, int j, int m, int n) {
if(i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == '0')
return;
grid[i][j] = '0';
dfs(grid, i+1, j, m, n);
dfs(grid, i-1, j, m, n);
dfs(grid, i, j+1, m, n);
dfs(grid, i, j-1, m, n);
}
};
代码(8.24 二刷自解)
#include <vector>
class Solution {
public:
int solve(vector<vector<char> >& grid) {
int m = grid.size(), n = grid[0].size();
int res = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j] == '1') {
res++;
dfs(grid, i, j, m, n);
}
}
}
return res;
}
void dfs(vector<vector<char>>& grid, int x, int y, int m, int n) {
if(x < 0 || y < 0 || x >= m || y >= n || grid[x][y] == '0')
return;
grid[x][y] = '0';
dfs(grid, x+1, y, m, n);
dfs(grid, x-1, y, m, n);
dfs(grid, x, y+1, m, n);
dfs(grid, x, y-1, m, n);
}
};
代码(9.11 三刷自解)
BFS
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int m = grid.size(), n = grid[0].size();
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
queue<vector<int>> mp;
int ans = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j] == '1') {
ans++;
grid[i][j] = '0';
mp.push({i,j});
while(!mp.empty()) {
auto front = mp.front();
mp.pop();
for(int k = 0; k < 4; k++) {
int dx = dir[k][0]+front[0], dy = dir[k][1] +front[1];
if(dx >= 0 && dx < m && dy >= 0 && dy < n && grid[dx][dy] == '1') {
grid[dx][dy] = '0';
mp.push({dx, dy});
}
}
}
}
}
}
return ans;
}
};
代码(12.14 四刷自解)
- Queue是用LinkList实现的,方法有remove、add、isEmpty
- Pair获取元素是通过
.getKey()
和.getValue()
- 在Java中,不能直接使用大括号{}来初始化一个泛型类型的数组列表。正确的初始化方式是使用Arrays.asList()方法。
class Solution {
public int numIslands(char[][] grid) {
if(grid == null || grid.length == 0)
return 0;
int m = grid.length, n = grid[0].length;
List<int[]> dirs = Arrays.asList(new int[]{1, 0}, new int[]{-1, 0}, new int[]{0, 1}, new int[]{0, -1});
int res = 0;
Queue<Pair<Integer, Integer>> q = new LinkedList<>();
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j] == '0') continue;
res++;
q.add(new Pair<Integer, Integer>(i, j));
grid[i][j] = '0';
while(!q.isEmpty()) {
Pair<Integer, Integer> front = q.remove();
for(int[] dir : dirs) {
int nx = front.getKey() + dir[0], ny = front.getValue() + dir[1];
if(nx < 0 || nx >= m || ny < 0 || ny >= n || grid[nx][ny] == '0') continue;
grid[nx][ny] = '0';
q.add(new Pair<Integer, Integer>(nx, ny));
}
}
}
}
return res;
}
}