C#C
C#2y ago
morry329#

IndexOutOfRangeException? Why??

I am analysing a solution for Spiral Matrix puzzle on LeetCode: https://leetcode.com/problems/spiral-matrix/

But I keep getting an IndexOutOfRange exception at this line
if (x >= r && !bol[y, x])


Could anyone kindly tell me why? Here is the whole solution code
public IList<int> SpiralOrder3(int[][] arr2D)
    {
        var ls = new List<int>();
        var count = 0;

        var bol = new bool[arr2D.Length,arr2D[0].Length];

        int x = 0, y = 0;
        var r = 0;

        while (count < arr2D.Length * arr2D[0].Length)
        {
            for (int i = 0; i < arr2D[0].Length - r; i++)
            {
                if (x < arr2D[0].Length - r && !bol[y, x])
                {
                    bol[y, x] = true;
                    ls.Add(arr2D[y][x++]);
                    count++;
                }
            }

            y++;
            x--;

            for (int i = 0; i < arr2D.Length - r; i++)
            {
                if (y < arr2D.Length - r && !bol[y, x])
                {
                    bol[y, x] = true;
                    ls.Add(arr2D[y++][x]);
                    count++;
                }
            }
            
            y--;
            x++;

            for (int i = 0; i < arr2D[0].Length - r; i++)
            {
                if (x >= r && !bol[y, x]) //EXCEPTION

                {
                    bol[y, x] = true;
                    ls.Add(arr2D[y][x--]);
                    count++;
                }
            }

            for (int i = 0; i < arr2D.Length - r; i++)
            {
                if (y >= r && !bol[y, x])
                {
                    bol[y, x] = true;
                    ls.Add(arr2D[y--][x]);
                    count++;
                }
            }

            x++;
            y++;
            r++;
        }

        return ls;
    }
`
LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
Was this page helpful?