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

总结

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

相关推荐
To_OC7 小时前
LC 207 课程表:刚学图论那会儿,我连这是拓扑排序都没看出来
javascript·算法·leetcode
To_OC7 小时前
LC 208 实现 Trie 前缀树:曾被名字劝退,写完发现是送分题
javascript·算法·leetcode
BadBadBad__AK9 小时前
线段树维护区间 k 次方和
c++·数学·算法·stl
_清歌21 小时前
DSpark 深度解读:DeepSeek-V4 如何用「半自回归」把推理速度提升 85%
算法
统计实现局1 天前
SVD 的三步走:双对角化、Givens 收敛、排序
算法
躬行见万象1 天前
《VLA 系列》UniLab 强化训练 | G1 机器人 |复现
算法
统计实现局1 天前
对称不定分解(Bunch-Kaufman):为什么 Cholesky 不够用
算法
统计实现局1 天前
dqrsl 拆解:拿着 QR 结果能算出哪 5 种东西
算法
统计实现局1 天前
为什么 Cholesky 求逆比 Gauss-Jordan 快一倍——行列式溢出防护详
算法