前言
###我做这类文章一个重要的目的还是给正在学习的大家提供方向和记录学习过程(例如想要掌握基础用法,该刷哪些题?)我的解析也不会做的非常详细,只会提供思路和一些关键点,力扣上的大佬们的题解质量是非常非常高滴!!!
习题
1.水域大小
题目链接:面试题 16.19. 水域大小 - 力扣(LeetCode)
分析:简单的dfs
java">class Solution {int[][] land;int n,m;int[][] flag;ArrayList<Integer> list = new ArrayList<>();int flag2 = 0;public int[] pondSizes(int[][] land) {this.land = land;n = land.length;m = land[0].length;flag = new int[n][m];for(int i = 0;i<n;i++){for(int j = 0;j<m;j++){if(flag[i][j]==0&&land[i][j]==0){flag2 = 0;recursion(i,j);// System.out.println("------------------------");list.add(flag2);}}}flag2 = 0;int[] ans = new int[list.size()];for(int a:list){ans[flag2++] = a;}Arrays.sort(ans);return ans;}public void recursion(int x,int y){// System.out.println(x+" "+y);flag[x][y] = 1;flag2++;if(x+1<n&&land[x+1][y]==0&&flag[x+1][y]==0){recursion(x+1,y);}if(x-1>=0&&land[x-1][y]==0&&flag[x-1][y]==0){recursion(x-1,y);}if(y+1<m&&land[x][y+1]==0&&flag[x][y+1]==0){recursion(x,y+1);}if(y-1>=0&&land[x][y-1]==0&&flag[x][y-1]==0){recursion(x,y-1);}if(x+1<n&&y+1<m&&land[x+1][y+1]==0&&flag[x+1][y+1]==0){recursion(x+1,y+1);}if(x+1<n&&y-1>=0&&land[x+1][y-1]==0&&flag[x+1][y-1]==0){recursion(x+1,y-1);}if(x-1>=0&&y+1<m&&land[x-1][y+1]==0&&flag[x-1][y+1]==0){recursion(x-1,y+1);}if(x-1>=0&&y-1>=0&&land[x-1][y-1]==0&&flag[x-1][y-1]==0){recursion(x-1,y-1);}}
}
2.主题空间
题目链接:LCS 03. 主题空间 - 力扣(LeetCode)
题面:
分析:dfs,只不过多一些考虑情况
代码:
java">class Solution {int n,m;int ans = 0;char[][] map;int[][] flag;int flag2 = 0;int islian = 0;public int largestArea(String[] grid) {n = grid.length;m = grid[0].length();map = new char[n][m];flag = new int[n][m];int count = 0;for(String str:grid){map[count++] = str.toCharArray();}for(int i = 1;i<n-1;i++){for(int j = 1;j<m-1;j++){if(map[i][j]!='0'&&flag[i][j]==0){flag2 = 0;islian = 0;recursion(i,j,map[i][j]);if(islian==0){ans = Math.max(ans,flag2);}}} }return ans;}public void recursion(int x,int y,char u){flag2++;flag[x][y] = 1;if(x==0||x==n-1||y==0||y==m-1)islian = 1;if(x+1<n){if(map[x+1][y]==u&&flag[x+1][y]==0){recursion(x+1,y,u);}if(map[x+1][y]=='0')islian=1;}if(x-1>=0){if(map[x-1][y]==u&&flag[x-1][y]==0){recursion(x-1,y,u);}if(map[x-1][y]=='0')islian = 1;}if(y+1<m){if(map[x][y+1]==u&&flag[x][y+1]==0){recursion(x,y+1,u);}if(map[x][y+1]=='0')islian = 1;}if(y-1>=0){if(map[x][y-1]==u&&flag[x][y-1]==0){recursion(x,y-1,u);}if(map[x][y-1]=='0')islian = 1;}}
}
后言
上面是力扣图论专题,下一篇是其他的习题,希望有所帮助,一同进步,共勉!