输入行和列的螺旋矩阵

Spiral matrix with entered rows and columns

作为一项作业,我必须创建一个螺旋矩阵,用户可以在其中输入行数和列数。 这是我目前的代码(大学一年级,所以不要对我太苛刻)

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

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

            // display matrica

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

            }
            Console.WriteLine();

        }
        Console.ReadLine();

我有点不知所措 this.I 知道如何使用相同的行数和列数来循环矩阵,但它应该是一个非方阵。

4 x 3 矩阵

8   9  10  1
7  12  11  2
6   5   4  3

5 x 2 矩阵

3  4
12 5
11 6
10 7 
9  8

这是我想出的解决方案 - 在社区的帮助下:)

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

由于这是一项作业,我不会为您完成所有工作,而是创建一个方形螺旋解决方案,以便您可以修改它以满足您的需要。使用此解决方案,假设用户输入单个值,例如 n;

 Console.WriteLine("Enter n");
            int n = int.Parse(Console.ReadLine());

            var x = new string[n, n];
            int m = n;





// Initialize current to 1
int current = 1;

    // Initialize the values for topLeft, topRight, bottomRight and bottomLeft
    int[] topLeft = { 0, 0 };
    int[] topRight = { 0, (n - 1) };
    int[] bottomRight = { (n - 1), (n - 1) };
    int[] bottomLeft = { (n - 1), 0 };

    int loops = (m % 2 == 0) ? (n / 2) : ((n / 2) + 1);

    for(int spiral = 0; spiral < loops; spiral++)
    {

        // Run loop 1 to fill top most row topLeft to topRight
        for(int i = topLeft[1]; i <= topRight[1]; i++)
        {

            x[topLeft[0], i] = CheckCurrent(current, n);

            // Increment current
            current++;
        }

        // Increment topLeft and topRight
        topLeft[0] += 1;
        topRight[0] += 1;

        // Run loop 2 to fill right most column from topRight to bottomRight
        for(int j = topRight[0]; j<=bottomRight[0]; j++)
        {

            x[j, topRight[1]] = CheckCurrent(current, n);
            current++;
        }

        // Decrement topRight and bottomRight
        topRight[1] -= 1;
        bottomRight[1] -= 1;

        // Run loop 3 to fill bottom most row from bottomRight to bottomLeft
        for(int k = bottomRight[1]; k>=bottomLeft[1]; k--)
        {

            x[bottomRight[0], k] = CheckCurrent(current, n);
            current++;
        }

        // Decrement bottomRight and bottomLeft
        bottomRight[0] -= 1;
        bottomLeft[0] -= 1;

        // Run loop 4 to fill left most column
        for(int l = bottomLeft[0]; l>= topLeft[0]; l--)
        {

            x[l, bottomLeft[1]] = CheckCurrent(current, n);
            current++;
        }

    // Increment/Decrement bottomLeft and TopLeft
    topLeft[1] += 1;
    bottomLeft[1] = bottomLeft[1] + 1;

}






 // Print the spiral
  for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                Console.Write("{0} ", x[i, j]);
            }

                Console.WriteLine();
            }

这个小方法是用来优化螺旋显示的。例如,如果我们有 4 作为 n,这意味着我们的最大值将为 16,因此我们必须在所有 1 位数字之前添加一个“0”以使它们成为 2 位数字。希望你明白了。但是你可以直接设置值而不使用该方法,除非你会有一个丑陋的螺旋..

/// <summary>
            /// Ensure all numbers in the spiral have thesame number of digits
            /// </summary>
            /// <param name="curr">The current numbers to be added to the spiral</param>
            /// <param name="n">The number the user entered</param>
            /// <returns></returns>
public static string CheckCurrent(int curr, int n)
    {
        int lenMaxNum = (n * n).ToString().Length;
        int lenCurr = curr.ToString().Length;

        string current = curr.ToString();

        int dif = lenMaxNum - lenCurr;

    for (int i = 0; i < dif; i++)
    {
        current = "0" + current;
    }

    return current;
}
using System;

namespace Exercise4
{
    class Program
    {
        static void Main(string[] args)
        {
            //int[,] matrix = new int[,] { { 1, 2, 3 }, { 5, 6, 7 }, { 9, 8, 7 } };
            int[,] matrix = new int[,] { { 1, 2, 3,4,5,6 }, { 20,21,22,23,24,7 }, { 19,32,33,34,25,8 },{18,31,36,35,26,9 }, { 17,30,29,28,27,10 } , { 16,15,14,13,12,11 } };
          
            Spiral s = new Spiral();
            s.Matrix = matrix;
            s.DisplayMatrix();
            s.WalkSpirally();
           

            int[,] matrix2 = new int[,] { { 1, 2, 3 }, { 5, 6, 7 }, { 9, 8, 7 } };
           
            
            Spiral s2 = new Spiral();
            s2.Matrix = matrix2;
            s2.DisplayMatrix();
            s2.WalkSpirally();
            Console.ReadLine();
        }
       
    }

    class Spiral
    {
        public int[,] Matrix;
        
        
       
        public void WalkSpirally()
        {
            int count = 0;
            int direction = 0;
            int loopCount = 0;
            int col = 0;
            int row = 0;
            int width = Matrix.GetLength(1);
            int height = Matrix.GetLength(0);
            while (count < Matrix.Length)
            {
                switch ((direction++) % 4)
                {
                    case 0://top side
                        for (; col < width - loopCount; ++col)
                        {
                            Console.Write(Matrix[row, col] + " ");
                            count++;
                        }
                        row++;
                        col--;
                        break;
                    case 1://right side

                        for (; row < height - loopCount; ++row)
                        {
                            Console.Write(Matrix[row, col] + " ");
                            count++;
                        }
                        col--;
                        row--;
                        break;
                    case 2://bottom side
                        for (; col > loopCount - 1; --col)
                        {
                            Console.Write(Matrix[row, col] + " ");
                            count++;
                        }
                        row--;
                        col++;
                        break;
                    case 3://left side

                        for (; row > loopCount; --row)
                        {
                            Console.Write(Matrix[row, col] + " ");
                            count++;
                        }

                        loopCount++;
                        col++;
                        row++;

                        break;

                }
            }
            Console.WriteLine();


        }

        public void DisplayMatrix()
        {
            for (int r = 0; r < Matrix.GetLength(1); r++)
            {
                for (int c = 0; c < Matrix.GetLength(0); c++)
                {
                    Console.Write("{0,6}", Matrix[r, c]);
                }
                Console.WriteLine();

            }
            Console.WriteLine();
        }
    }
}