前言
###我做这类文章一个重要的目的还是给正在学习的大家提供方向和记录学习过程(例如想要掌握基础用法,该刷哪些题?)我的解析也不会做的非常详细,只会提供思路和一些关键点,力扣上的大佬们的题解质量是非常非常高滴!!!
习题
tips:板子题就不分析了
1.网格图中鱼的最大数目
题目链接:2658. 网格图中鱼的最大数目 - 力扣(LeetCode)
题面:
代码:
java">class Solution {int[][] grid;int n,m;int flag[][];int flag2;int ans = 0;public int findMaxFish(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]>0&&flag[i][j]==0){flag2 = 0;recursion(i,j);ans = Math.max(ans,flag2);}}}return ans;}public void recursion(int x,int y){flag[x][y] = 1;flag2+=grid[x][y];if(x+1<n&&grid[x+1][y]>0&&flag[x+1][y]==0){recursion(x+1,y);}if(y+1<m&&grid[x][y+1]>0&&flag[x][y+1]==0){recursion(x,y+1);}if(x-1>=0&&grid[x-1][y]>0&&flag[x-1][y]==0){recursion(x-1,y);}if(y-1>=0&&grid[x][y-1]>0&&flag[x][y-1]==0){recursion(x,y-1);}}
}
2.边界着色
题目链接:1034. 边界着色 - 力扣(LeetCode)
题面:
代码:
java">class Solution {int[][] grid;int color;int n,m;int[][] flag;public int[][] colorBorder(int[][] grid, int row, int col, int color) {this.grid = grid;this.color = color;n = grid.length;m = grid[0].length;flag = new int[n][m];recursion(row,col);return grid;}public void recursion(int x,int y){flag[x][y] = 1;int flag2 = 0;if(x+1<n){if(grid[x+1][y]==grid[x][y]&&flag[x+1][y]==0){recursion(x+1,y);}if(grid[x+1][y]!=grid[x][y]&&flag[x+1][y]==0){flag2 =1;}}if(x-1>=0){if(grid[x-1][y]==grid[x][y]&&flag[x-1][y]==0){recursion(x-1,y);}if(grid[x-1][y]!=grid[x][y]&&flag[x-1][y]==0){flag2 =1;}}if(y-1>=0){if(grid[x][y-1]==grid[x][y]&&flag[x][y-1]==0){recursion(x,y-1);}if(grid[x][y-1]!=grid[x][y]&&flag[x][y-1]==0){flag2 =1;}}if(y+1<m){if(grid[x][y+1]==grid[x][y]&&flag[x][y+1]==0){recursion(x,y+1);}if(grid[x][y+1]!=grid[x][y]&&flag[x][y+1]==0){flag2 =1;}}// System.out.println(x+" "+y+" "+flag2);if(flag2==1||x==n-1||x==0||y==m-1||y==0){grid[x][y] =color;}}
}
后言
上面是力扣图论专题,下一篇是其他的习题,希望有所帮助,一同进步,共勉!