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

Leetcode 733: FloodFill代码中y > image[x].Length-1的含义疑问

Leetcode 733 Flood Fill代码中y > image[x].Length - 1的含义澄清

你给出的C#代码如下:

public class Solution {
    public int[][] FloodFill(int[][] image, int sr, int sc, int color) {
        if(image[sr][sc] == color) return image;
        Fill(image,sr,sc,color,image[sr][sc]);
        return image;
    }
    
    private void Fill(int[][] image,int x, int y, int color, int oldColor) {
        if(x < 0 || y < 0 || x > image.Length - 1 || y > image[x].Length - 1 || image[x][y] == color || image[x][y] != oldColor) return;
        
        image[x][y] = color;
        
        Fill(image,x + 1,y,color,oldColor);
        Fill(image,x - 1,y,color,oldColor);
        Fill(image,x,y + 1,color,oldColor);
        Fill(image,x,y - 1,color,oldColor);
    }
}

你的猜测完全正确,y > image[x].Length - 1就是第x行的列边界判断,具体细节:

  • 二维数组image中,image.Length代表总行数,x > image.Length -1用于检查行索引x是否超出最大行下标(数组下标从0开始,最后一行的下标为总行数-1)。
  • image[x]指代二维数组里的第x行,它本身是一个一维数组,image[x].Length就是该行的列数,因此第x行的最大列下标是image[x].Length -1。y > image[x].Length -1就是判断列索引y是否超过当前行的有效列范围,防止出现数组越界访问的错误。

举个实例:如果第x行有4列(image[x].Length = 4),那么有效列下标是0、1、2、3,当y=4时,这个条件会触发,直接返回,避免访问不存在的image[x][4]引发运行时错误。

和y < 0配合,这两个条件就把列索引y限制在了当前行的合法范围内。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:35:24