【问题标题】:Spiral matrix with entered rows and columns具有输入行和列的螺旋矩阵
【发布时间】:2017-09-07 14:00:00
【问题描述】:

作为一项任务,我必须创建一个螺旋矩阵,用户在其中输入行数和列数。 这是我迄今为止的代码(大学学习的第一年,所以不要对我太苛刻)

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

我对如何做到这一点有点迷茫。我知道如何用相同的行数和列数循环矩阵,但它应该是一个非方阵。

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

【问题讨论】:

  • 我仍然在这里寻求帮助...

标签: c# .net matrix spiral


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      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();
              }
          }
      }
      
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多