leecode练习
733.图像渲染
这道题题目很绕,其实就是一道深度优先搜索,将像素值相同的所有连通区域修改成新的像素值,只需要记录旧的像素值进行递归遍历即可。
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
int oldColor = image[sr][sc];
dfs(image,sr,sc, oldColor,newColor);
return image;
}
public void dfs(int[][] image, int sr, int sc, int oldColor, int newColor) {
if(sr < 0 || sc < 0 || sr >= image.length || sc >= image[0].length || image[sr][sc] != oldColor || oldColor == newColor) {
return;
}
image[sr][sc] = newColor;
dfs(image, sr + 1, sc, oldColor, newColor);
dfs(image, sr - 1, sc, oldColor, newColor);
dfs(image, sr, sc + 1, oldColor, newColor);
dfs(image, sr, sc - 1, oldColor, newColor);
}
695.岛屿最大面积
这道题需要注意的就是找起始点,还有记录遍历过的岛屿数。
public int maxAreaOfIsland(int[][] grid) {
int row = grid.length;
int col = grid[0].length;
int max = 0;
for(int i=0; i<row; i++) {
for(int j=0; j<col; j++) {
// 深度优先遍历
max = Math.max(max, dfs(grid, i, j));
}
}
return max;
}
int dfs(int[][] grid, int x, int y) {
// 边界检查
// 数组为0 直接返回
if(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] == 0) {
return 0;
}
// 不为0 即为1 修改成0 避免下次再计算到
grid[x][y] = 0;
// 当前出发, 向上下左右四个方向出发
return 1 + dfs(grid, x+1, y) + dfs(grid, x-1, y) + dfs(grid, x, y+1) + dfs(grid, x, y-1);
}