LeetCode第2658题 - 网格图中鱼的最大数目

题目

解答

java 复制代码
class Solution {
  public int findMaxFish(int[][] grid) {
    int maxCount = Integer.MIN_VALUE;
    int m = grid.length;
    int n = grid[0].length;
    for (int i = 0; i < m; ++i) {
      for (int j = 0; j < n; ++j) {
        int value = grid[i][j];
        if (value == 0) {
          continue;
        }

        int count = bfs(grid, i, j);
        maxCount = Math.max(maxCount, count);
      }
    }

    return maxCount == Integer.MIN_VALUE ? 0 : maxCount;
  }

  int bfs(int[][] grid, int row, int column) {
    int m = grid.length;
    int n = grid[0].length;

    int count = 0;

    LinkedList<int[]> queue = new LinkedList<>();
    queue.add(new int[]{row, column});

    while (!queue.isEmpty()) {
      int[] position = queue.removeFirst();
      int r = position[0];
      int c = position[1];
      if (r < 0 || r >= m || c < 0 || c >= n) {
        continue;
      }

      int value = grid[r][c];
      if (value == 0) {
        continue;
      }

      count += value;
      grid[r][c] = 0;
      queue.add(new int[]{r, c + 1});
      queue.add(new int[]{r, c - 1});
      queue.add(new int[]{r + 1, c});
      queue.add(new int[]{r - 1, c});
    }

    return count;
  }
}

总结

使用广度优先算法,遍历地图。

相关推荐
冻柠檬飞冰走茶6 小时前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
文丑颜不良啊7 小时前
LeetCode2161~2180题目解析
java·leetcode
雪落漂泊7 小时前
C++算法 二分查找篇(上)
开发语言·c++·算法
文丑颜不良啊8 小时前
LeetCode2141~2160题目解析
java·leetcode
LabVIEW开发9 小时前
LabVIEW 连接板:28 个端子怎么排,优先级怎么定
java·算法·labview
严肃小白兔10 小时前
MATLAB 数值计算中的精度与误差问题:浮点运算、误差传播与数值稳定性
人工智能·算法·matlab
青少儿编程课堂11 小时前
蓝桥杯青少组图形化省考报名倒计时·全国青少年信息素养大赛·电子学会图形化考级:校园黑白棋人机对战解析
c++·python·算法·bfs·信息学竞赛
jktantan12 小时前
注解式脱敏:用 Jackson 的 ContextualSerializer 做字段级策略(一)
spring boot·后端·算法·spring cloud·系统架构
Dream it possible!1 天前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊1 天前
算法之双指针系列(一)
算法·leetcode