You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

获取数组中单元格所有邻居时避免数组越界异常求助

问题分析与修复方案
  • 错误根源:你的边界判断逻辑完全错误。第二个if里的c <= (col + 1) && r <= (row + 1)根本不是在检查是否超出网格边界,而是在判断是否不超过当前单元格的右下邻位。比如处理最后一行(索引row=2)时,row+1=3,但你的网格只有3行(索引范围0-2),这时候r<=3会允许r=3,直接触发数组越界。

  • 正确的边界判断逻辑:应该用网格的实际尺寸来限制索引范围:

    • 行索引r必须满足 0 <= r < landscape.length(landscape.length是网格总行数)
    • 列索引c必须满足 0 <= c < landscape[r].length(假设所有行的列数一致,也可以提前定义变量存储总列数)
  • 修正后的完整代码:

public ArrayList<Cell> getNeighbors(int row, int col) {
    ArrayList<Cell> neighbors = new ArrayList<Cell>();
    int totalRows = landscape.length;
    int totalCols = landscape[0].length; // 假设所有行列数相同,若不同需单独处理每行
    
    for (int r = row - 1; r <= row + 1; r++) {
        for (int c = col - 1; c <= col + 1; c++) {
            // 跳过当前单元格本身
            if (r == row && c == col) {
                continue;
            }
            // 检查索引是否在网格有效范围内
            if (r >= 0 && r < totalRows && c >= 0 && c < totalCols) {
                neighbors.add(landscape[r][c]);
            }
        }
    }
    return neighbors;
}
  • 额外优化说明:
    • 提前存储总行数和总列数,避免循环中重复调用landscape.length,提升代码效率。
    • 将!(r == row && c == col)改为if (r == row && c == col) continue;,逻辑更直观,可读性更强。

内容的提问来源于stack exchange,提问作者displayName

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 09:31:03