Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class SpiralMatrix
- {
- public static void Main()
- {
- //Initiate a variable for the size of the matrix
- int n;
- //User input
- Console.Write("Input an integer number in the interval [1;19]: ");
- //A variable to check for valid input
- bool valid = Int32.TryParse(Console.ReadLine(), out n);
- //Input validation
- if (valid && (n > 0 && n < 20))
- {
- //Initiation of the matrix
- int[,] num = new int[n, n];
- //Initiation of coordinates and direction
- int x = 0, y = 0, direction = 0;
- //For-loop for filling up the matrix
- for (int i = 0; i < n * n; i++)
- {
- //Write on a particular position in the matrix the value of the counter of the for-loop. The starting position is (0,0) and the first value is 1.
- num[x, y] = i + 1;
- //Depending on the direction of movement there are 4 different cases.
- switch (direction)
- {
- //Direction down
- case 0:
- //If x is lower the the maxXBound and the position is empty increase x by 1 and start the loop again. This will continue until row 1 is full
- if (x < n - 1 && num[x + 1, y] == 0)
- {
- x++;
- }
- //When row 1 is full the direction changes:
- else
- {
- direction = (++direction) % 4;
- y++;
- }
- break;
- //Direction right
- case 1:
- if (y < n - 1 && num[x, y + 1] == 0)
- {
- y++;
- }
- else
- {
- direction = (++direction) % 4;
- x--;
- }
- break;
- //Direction up
- case 2:
- if (x > 0 && num[x - 1, y] == 0)
- {
- x--;
- }
- else
- {
- direction = (++direction) % 4;
- y--;
- }
- break;
- //Direction left
- case 3:
- if (y > 0 && num[x, y - 1] == 0)
- {
- y--;
- }
- else
- {
- direction = (++direction) % 4;
- x++;
- }
- break;
- default:
- Console.WriteLine("Invalid direction value!");
- break;
- }
- }
- int align = ((n * n).ToString()).Length;
- for (int i = 0; i < n; i++)
- {
- for (int j = 0; j < n; j++)
- {
- Console.Write("{0}", ((num[j, i].ToString()).PadRight(align / 2)).PadLeft(align + 1));
- }
- Console.WriteLine();
- }
- }
- else
- {
- Console.WriteLine("Invalid input data!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement