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

总结

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

相关推荐
studyForMokey10 分钟前
【Android 面试】Paging3
android·面试·职场和发展
Mister Leon29 分钟前
Nvidia Orin AGX实战之从量化到蒸馏:在 Orin 上落地的大模型压缩实战
人工智能·算法·机器学习
aqiu11111130 分钟前
蓝桥杯真题复盘:Fibonacci 数列与黄金分割(C++ 算法详解)
c++·算法·蓝桥杯
.道阻且长.32 分钟前
Linux软件包管理器
linux·运维·ubuntu·职场和发展·centos
考研保研资料分享33 分钟前
211英语专业跨保清华法学:2022年法学面试与口译考核复盘
面试·职场和发展
phoenix@Capricornus35 分钟前
LDA 协方差矩阵(MATLAB `fitcdiscr`)
算法·matlab·矩阵
青少儿编程课堂39 分钟前
蓝桥杯·全国青少年信息素养大赛·电子学会C/C++考级:拓扑排序课程表排课解析
c++·python·算法·bfs·信息学竞赛
考研保研资料分享42 分钟前
2024双非材料保研复旦:五校面试题与科研复盘
面试·职场和发展
救救孩子把10 小时前
AI面试八股文-21_21-多模态Agent面试题-Vision-Language-Agent
人工智能·面试·职场和发展·llava·多模态agent
HPtiger10 小时前
数据结构——选择排序
数据结构·算法·排序算法