Search code examples
c#matrixspiral

Non square spiral matrix not printing correctly


I am having issues with this assignment I have. I am to print a spiral matrix which cannot be square, in other words the user should input the number of rows and columns.

        Console.Write("Enter n: ");
        int n = int.Parse(Console.ReadLine());
        Console.Write("Enter m: ");
        int m = int.Parse(Console.ReadLine());
        int[,] matrix = new int[n,m];
        int row = 0;
        int col = 0;
        string direction = "right";
        int maxRotations = n * m;

        for (int i = 1; i <= maxRotations; i++)
        {
            if (direction == "right" && (col > n - 1 || matrix[row, col] != 0))
            {
                direction = "down";
                col--;
                row++;
            }
            if (direction == "down" && (row > n - 1 || matrix[row, col] != 0))
            {
                direction = "left";
                row--;
                col--;
            }
            if (direction == "left" && (col < 0 || matrix[row, col] != 0))
            {
                direction = "up";
                col++;
                row--;
            }

            if (direction == "up" && row < 0 || matrix[row, col] != 0)
            {
                direction = "right";
                row++;
                col++;
            }

            matrix[row, col] = i;

            if (direction == "right")
            {
                col++;
            }
            if (direction == "down")
            {
                row++;
            }
            if (direction == "left")
            {
                col--;
            }
            if (direction == "up")
            {
                row--;
            }
        }

        // displej matrica

        for (int r = 0; r < n; r++)
        {
            for (int c = 0; c < m ; c++)
            {
                Console.Write("{0,4}", matrix[r,c]);
            }
            Console.WriteLine();

        }
        Console.ReadLine();
    }

My issue currently is that is not printing and at the same is printing in a spiral. In other words the spiral is kind of messed up. If i run the code and enter 4 as the number of rows and 6 as the number of columns I get the following:

1  2  3  4 0 24
12 13 14 5 0 23
11 16 17 18 19 22
10  9  8  7 20 21

What am i doing wrong?


Solution

  • Your first two conditions check the same boundary (n):

    if (direction == "right" && (col > n - 1 || matrix[row, col] != 0))
    if (direction == "down" && (row > n - 1 || matrix[row, col] != 0))
    

    I guess for "right" your boundary should be m.

    if (direction == "right" && (col > m - 1 || matrix[row, col] != 0))
    

    That's why it is "turning" early: n is 4. And that's exactly where it is turning. The rest are all follow-up errors.