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

总结

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

相关推荐
码完就睡21 小时前
数据结构——树、二叉树基础概念
数据结构·算法
VL——MOESR1 天前
【LuoguP1967】货车运输【生成树】【倍增】
c++·算法·题解·倍增·生成树
手写码匠1 天前
华为云Flexus+DeepSeek征文|Agent 记忆系统实战:用 DeepSeek-R1/V3 + Dify 会话变量打造跨会话长期记忆
人工智能·深度学习·算法·aigc
Olafur_zbj1 天前
【AI】CUDA编程中的维度
人工智能·算法
坚持编程的菜鸟1 天前
模拟实现memcpy
c语言·算法·模拟实现my_memcpy
wabs6661 天前
关于图论【最短路径之Bellman_ford 算法|卡码网94.城市间货物运输的思考】
数据结构·算法·图论·卡码网·bellman_ford·求最短路径
MrZhao4001 天前
On-Policy Distillation(OPD):为什么大模型后训练要在学生自己的轨迹上蒸馏?
算法
朱峥嵘(朱髯)1 天前
数据库如何根据全表 NDV 估算子集的 NDV
数据库·算法
jjjava2.01 天前
牛客算法题(第四期)
算法
雪碧聊技术1 天前
力扣 回溯法 | LCR 020. 回文子串
javascript·算法·leetcode