非方形螺旋矩阵无法正确打印

时间:2017-09-13 11:36:38

标签: c# matrix spiral

我遇到了这项任务的问题。我要打印一个不能是正方形的螺旋矩阵,换句话说,用户应该输入行数和列数。

        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();
    }

我目前的问题是不打印,同时是螺旋打印。换句话说,螺旋是混乱的。 如果我运行代码并输入4作为行数,输入6作为列数我得到以下内容:

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

我做错了什么?

1 个答案:

答案 0 :(得分:0)

前两个条件检查相同的边界(n):

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

我猜对于#34;对&#34;你的边界应该是m

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

这就是&#34;转向&#34;早期:n是4.那就是它正好转向的地方。其余的都是后续错误。