Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace Additional_NON_Required_Advanced_Problem_Spiral_Matrix
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.Write("Enter a number: ");
- byte n = byte.Parse(Console.ReadLine());
- int[,] matrix = new int[n, n];
- sbyte row = 0;
- sbyte col = -1;
- string direction = "right";
- Console.WriteLine();
- for (int i = 1; i <= n * n; i++)
- {
- if (direction == "right")
- {
- if (matrix[row, ++col] == 0)
- {
- matrix[row, col] = i;
- }
- if (col + 1 >= n || matrix[row, col + 1] != 0)
- {
- direction = "down";
- }
- }
- else if (direction == "down")
- {
- if (matrix[++row, col] == 0)
- {
- matrix[row, col] = i;
- }
- if (row + 1 >= n || matrix[row + 1, col] != 0)
- {
- direction = "left";
- }
- }
- else if (direction == "left")
- {
- if (matrix[row, --col] == 0)
- {
- matrix[row, col] = i;
- }
- if (col - 1 < 0 || matrix[row, col - 1] != 0)
- {
- direction = "up";
- }
- }
- else if (direction == "up")
- {
- if (matrix[--row, col] == 0)
- {
- matrix[row, col] = i;
- }
- if (row - 1 < 0 || matrix[row - 1, col] != 0)
- {
- direction = "right";
- }
- }
- }
- for (int i = 0; i < matrix.GetLength(0); i++)
- {
- for (int j = 0; j < matrix.GetLength(1); j++)
- {
- Console.Write("{0,4}", matrix[i, j] + " ");
- }
- Console.WriteLine();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement