DFS专题:力扣岛屿问题
一、岛屿数量
题目链接: 200.岛屿数量
题目描述
代码思路
使用深度优先搜索,对每一个网格点进行判断,如果为未搜索过的’1’,则使岛屿数加一,并将与其相连的‘1’都进行标记,确保每次搜索到1都是一个新的岛屿。
代码纯享版
class Solution {public int numIslands(char[][] grid) {int len = grid.length; int wide = grid[0].length; int sum = 0;for(int i = 0; i < len; i++){for(int j = 0; j < wide; j++){if(grid[i][j] == '1'){sum++;dfs(grid, i, j);}}}return sum;}void dfs(char[][] grid, int i, int j){int len = grid.length;int wide = grid[0].length;if(i < 0 || i >= len || j < 0 || j >= wide || grid[i][j] != '1'){return;}grid[i][j] = '2'; dfs(grid, i - 1, j);dfs(grid, i + 1, j);dfs(grid, i, j - 1);dfs(grid, i, j + 1);}
}
代码逐行解析版
class Solution {public int numIslands(char[][] grid) {int len = grid.length; //岛屿长度int wide = grid[0].length; //岛屿宽度int sum = 0; //岛屿总数//遍历岛屿每一个位置for(int i = 0; i < len; i++){for(int j = 0; j < wide; j++){ if(grid[i][j] == '1'){ //如果为陆地sum++; //岛屿总数加一dfs(grid, i, j); //dfs}}}return sum;}//深度搜索所有连接在一起的'1',将其变为'2'//grid[i][j] == '0' 水//grid[i][j] == '1' 未搜索的陆地//grid[i][j] == '2' 已搜索的陆地void dfs(char[][] grid, int i, int j){int len = grid.length;int wide = grid[0].length;//排除2种情况//1.超出网格范围的搜索//2.不是未搜索的陆地if(i < 0 || i >= len || j < 0 || j >= wide || grid[i][j] != '1'){ return;}grid[i][j] = '2'; //将grid[i][j] == '1'的情况标记为'2'//上下左右四个方位的搜索dfs(grid, i - 1, j);dfs(grid, i + 1, j);dfs(grid, i, j - 1);dfs(grid, i, j + 1);}
}