1、前言
2、思路
思路有两种,DFS 和 BFS。DFS 主要从当前一个点出发,递归遍历上下左右。
BFS 思路与 DFS 差不多,只不过也是遍历当前节点的上下左右,这种 BFS 思路可以做很多关于这种二维数组的题,比如腐烂的橘子。虽然后面的 dfs 思路在 leetcode 超时了,但是这算是一个很通俗的思路,还是需要掌握的。
3、代码
/**思路:深度优先遍历**/
class Solution {
public int numIslands(char[][] grid) {
if(grid.length == 0 || grid[0].length == 0){
return 0;
}
int m = grid.length;
int n = grid[0].length;
int count = 0;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(grid[i][j] == '1'){
dfs(grid, i, j);
count++;
}
}
}
return count;
}
private void dfs(char[][] grid, int i, int j){
if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0'){
return;
}
grid[i][j] = '0';
dfs(grid, i + 1, j);
dfs(grid, i, j + 1);
dfs(grid, i - 1, j);
dfs(grid, i, j - 1);
}
}
BFS:
/**思路:广度优先遍历**/
class Solution {
public int numIslands(char[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0){
return 0;
}
int sum = 0, m = grid.length, n = grid[0].length;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(grid[i][j] == '1'){
bfs(grid, i, j);
sum++;
}
}
}
return sum;
}
private void bfs(char[][] grid, int one, int two){
if(one < 0 || one >= grid.length || two < 0 || two >= grid[0].length || grid[one][two] == '0'){
return;
}
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{one, two});
int m = grid.length, n = grid[0].length;
while(!queue.isEmpty()){
int size = queue.size();
for(int p = 0; p < size; p++){
int[] arr = queue.poll();
int i = arr[0], j = arr[1];
grid[i][j] = '0';
if(i - 1 >= 0 && i - 1 < m && j >= 0 && j < n && grid[i - 1][j] == '1'){
queue.add(new int[]{i - 1, j});
}
if(i + 1 < m && i + 1 >= 0 && j >= 0 && j < n && grid[i + 1][j] == '1'){
queue.add(new int[]{i + 1, j});
}
if(i >= 0 && i < m && j - 1 >= 0 && j - 1 < n&& grid[i][j - 1] == '1'){
queue.add(new int[]{i, j - 1});
}
if(i >= 0 && i < m && j + 1 >= 0 && j + 1 < n && grid[i][j + 1] == '1'){
queue.add(new int[]{i, j + 1});
}
}
}
}
}