'Spiral matrix with entered rows and columns

As an assignment i have to create a spiral matrix where the user inputs the number of rows and number of columns. This is my code for far (first year in college studies, so don't be too hard on me)

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

I am a bit lost as how to do this.I know how to loop the matrix with the same number for the rows and columns but it should be a non-square matrix.

4 x 3 matrix

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

5 x 2 matrix

3  4
12 5
11 6
10 7 
9  8


Solution 1:[1]

Here is the solution I came up with - with some help from the community here :)

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

Solution 2:[2]

Since this is an assignment, I won't do all the work for you, I will create a solution for a square spiral instead so you can modify it to suit your needs. With this solution, a user is suppose to enter a single value e.g 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();
            }

This small method is used to optimize the spiral display. E.g if we have 4 as n, it means our max value will be 16 so we have to add one "0" before all 1 digit numbers to make them 2 digits. Hope you get the idea. But you can set the values directly without using the method except you will have an ugly spiral..

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

Solution 3:[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();
        }
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Novica Josifovski
Solution 2
Solution 3 Saige Zhang