Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class SpiralMatrix
- {
- static void Main()
- {
- Console.Write("Enter a number in range[2...20]: ");
- int num = int.Parse(Console.ReadLine());
- int[,] spiralMatrix = new int[num, num];
- int row = 0;
- int col = 0;
- int number = 1;
- for (int i = 1; i<= num * num; i++)
- {
- while(true)
- {
- spiralMatrix[row, col] = number;
- if (col + 1 < num && spiralMatrix[row, col + 1] == 0)
- {
- ++col;
- ++number;
- }
- else break;
- }
- while(true)
- {
- spiralMatrix[row, col] = number;
- if (row + 1 < num && spiralMatrix[row + 1, col] == 0)
- {
- ++row;
- ++number;
- }
- else break;
- }
- while(true)
- {
- spiralMatrix[row, col] = number;
- if (col - 1 >= 0 && spiralMatrix[row, col - 1] == 0)
- {
- --col;
- ++number;
- }
- else break;
- }
- while (true)
- {
- spiralMatrix[row, col] = number;
- if (row - 1 >= 0 && spiralMatrix[row - 1, col] == 0)
- {
- --row;
- ++number;
- }
- else break;
- }
- }
- for (int printRow = 0; printRow < num; printRow++)
- {
- for (int printCol = 0; printCol < num; printCol++)
- {
- Console.Write("{0,4} ", spiralMatrix[printRow, printCol]);
- }
- Console.WriteLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement