leetcode算法入门 第七天 广度优先搜索/深度优先搜索

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);

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值