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

总结

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

相关推荐
Gorway2 小时前
解析残差网络 (ResNet)
算法
拖拉斯旋风3 小时前
LeetCode 经典算法题解析:优先队列与广度优先搜索的巧妙应用
算法
Wect3 小时前
LeetCode 207. 课程表:两种解法(BFS+DFS)详细解析
前端·算法·typescript
灵感__idea16 小时前
Hello 算法:众里寻她千“百度”
前端·javascript·算法
Wect1 天前
LeetCode 130. 被围绕的区域:两种解法详解(BFS/DFS)
前端·算法·typescript
NAGNIP2 天前
一文搞懂深度学习中的通用逼近定理!
人工智能·算法·面试
颜酱2 天前
单调栈:从模板到实战
javascript·后端·算法
CoovallyAIHub2 天前
仿生学突破:SILD模型如何让无人机在电力线迷宫中发现“隐形威胁”
深度学习·算法·计算机视觉
CoovallyAIHub2 天前
从春晚机器人到零样本革命:YOLO26-Pose姿态估计实战指南
深度学习·算法·计算机视觉
CoovallyAIHub2 天前
Le-DETR:省80%预训练数据,这个实时检测Transformer刷新SOTA|Georgia Tech & 北交大
深度学习·算法·计算机视觉