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

数组索引越界异常求助:完美扫描判断C#代码问题排查

数组扫描逻辑的索引越界问题分析与修复

我正在实现一种数组扫描逻辑,需要按照数组内存储的数值跳转索引,以此判断数组是否为「完美扫描」,但运行代码时抛出Index was outside the bounds of the array.(数组索引越界)异常,找不到原因,老师也没法解决。

示例说明

  • 完美扫描示例:![这是完美扫描的示例]
  • 非完美扫描示例:![这不是完美扫描]

原问题代码

using System;
                    
public class Program
{
    public static bool IsPerfect(int[] arr)
        {
            int next=0, done=0,i;

            while (done == 0)
            {
                i = arr[next];
                arr[next] = 10;
                next = arr[i];

                if (i == 0)
                    done = 1;
            }

            for(int j = 0; j < arr.Length; j++)            
                if (arr[j] != 10)
                    return false;               
            return true;

          
        }
        
    
    public static void Main()
        {
            int[] arr = { 3, 0, 1, 4, 2 };
            if (IsPerfect(arr) == true)
                Console.WriteLine("is perfect");
            if (IsPerfect(arr) == false)
                Console.WriteLine("boooo");

        }
}

问题根源

  1. 破坏原数组导致跳转失效:扫描时把访问过的位置设为10,后续访问该位置时,arr[i]取到10,而数组长度为5,最大索引是4,直接触发越界。
  2. 循环终止逻辑错误:只有当i == 0时才终止循环,若跳转链没回到0或没覆盖所有元素,循环会无限执行直到越界。
  3. 重复调用破坏数组:Main方法里连续两次调用IsPerfect,第一次调用已经把数组改成全10,第二次调用时数组内容完全被破坏,必然出错。

修复后的代码

using System;

public class Program
{
    public static bool IsPerfect(int[] arr)
    {
        bool[] visited = new bool[arr.Length];
        int current = 0;
        int visitedCount = 0;

        while (!visited[current])
        {
            visited[current] = true;
            visitedCount++;
            // 提前检查下一个索引是否合法,避免越界
            if (arr[current] < 0 || arr[current] >= arr.Length)
            {
                return false;
            }
            current = arr[current];
        }

        // 完美扫描要求:最终回到起点,且所有元素都被访问过
        return current == 0 && visitedCount == arr.Length;
    }

    public static void Main()
    {
        int[] arr = { 3, 0, 1, 4, 2 };
        bool result = IsPerfect(arr);
        Console.WriteLine(result ? "is perfect" : "boooo");
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:30:49