前言
###我做这类文章一个重要的目的还是给正在学习的大家提供方向和记录学习过程(例如想要掌握基础用法,该刷哪些题?)我的解析也不会做的非常详细,只会提供思路和一些关键点,力扣上的大佬们的题解质量是非常非常高滴!!!
习题
1.岛屿数量
题目链接:200. 岛屿数量 - 力扣(LeetCode)
分析:使用flag标记已经搜过的1点,每找到一个1答案加一,然后用dfs将所有相邻的1标记
java">class Solution {char[][] grid;int[][] flag;int n,m;int ans = 0;public int numIslands(char[][] grid) {this.grid = grid;n = grid.length;m = grid[0].length;flag = new int[n][m];for(int i = 0;i<n;i++){for(int j = 0;j<m;j++){if(grid[i][j]=='1'&&flag[i][j]==0){ans++;recursion(i,j);}}}return ans;}public void recursion(int x,int y){flag[x][y] = 1;if(x+1<n&&grid[x+1][y]=='1'&&flag[x+1][y]==0){recursion(x+1,y);}if(x-1>=0&&grid[x-1][y]=='1'&&flag[x-1][y]==0){recursion(x-1,y);}if(y+1<m&&grid[x][y+1]=='1'&&flag[x][y+1]==0){recursion(x,y+1);}if(y-1>=0&&grid[x][y-1]=='1'&&flag[x][y-1]==0){recursion(x,y-1);}}
}
2.岛屿的最大面积
题目链接:695. 岛屿的最大面积 - 力扣(LeetCode)
题面:
分析:dfs
代码:
java">class Solution {int[][] grid;int ans = 0;int n,m;int[][] flag;int flag2 = 0;public int maxAreaOfIsland(int[][] grid) {this.grid = grid;n = grid.length;m = grid[0].length;flag = new int[n][m];for(int i = 0;i<n;i++){for(int j = 0;j<m;j++){if(grid[i][j]==1&&flag[i][j]==0){flag2 = 1;recursion(i,j);ans = Math.max(ans,flag2);}}}return ans;}public void recursion(int x,int y){// System.out.println(x+" "+y+" "+count);// System.out.println(x+" "+y+" "+flag2);flag[x][y] = 1;if(x+1<n&&grid[x+1][y]==1&&flag[x+1][y]==0){flag2++;recursion(x+1,y); }if(x-1>=0&&grid[x-1][y]==1&&flag[x-1][y]==0){flag2++;recursion(x-1,y);}if(y+1<m&&grid[x][y+1]==1&&flag[x][y+1]==0){flag2++;recursion(x,y+1);}if(y-1>=0&&grid[x][y-1]==1&&flag[x][y-1]==0){flag2++;recursion(x,y-1);}}
}
后言
上面是力扣图论专题,下一篇是其他的习题,希望有所帮助,一同进步,共勉!