Advertisement
dentia

SpiralMatrix

Mar 25th, 2014
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.82 KB | None | 0 0
  1. using System;
  2.  
  3. class SpiralMatrix
  4. {
  5.     static void Main()
  6.     {
  7.         Console.Write("Enter a number in range[2...20]: ");
  8.         int num = int.Parse(Console.ReadLine());
  9.        int[,] spiralMatrix = new int[num, num];
  10.         int row = 0;
  11.         int col = 0;
  12.         int number = 1;
  13.  
  14.         for (int i = 1; i<= num * num; i++)
  15.         {
  16.            
  17.             while(true)
  18.             {
  19.                 spiralMatrix[row, col] = number;
  20.                 if (col + 1 < num && spiralMatrix[row, col + 1] == 0)
  21.                 {
  22.                     ++col;
  23.                     ++number;
  24.                 }
  25.                 else break;
  26.             }
  27.           while(true)
  28.           {
  29.               spiralMatrix[row, col] = number;
  30.               if (row + 1 < num && spiralMatrix[row + 1, col] == 0)
  31.               {
  32.                   ++row;
  33.                   ++number;
  34.               }
  35.               else break;
  36.           }
  37.           while(true)
  38.           {
  39.               spiralMatrix[row, col] = number;
  40.               if (col - 1 >= 0 && spiralMatrix[row, col - 1] == 0)
  41.               {
  42.                   --col;
  43.                   ++number;
  44.               }
  45.               else break;
  46.           }
  47.           while (true)
  48.           {
  49.               spiralMatrix[row, col] = number;
  50.               if (row - 1 >= 0 && spiralMatrix[row - 1, col] == 0)
  51.               {
  52.                   --row;
  53.                   ++number;
  54.               }
  55.               else break;
  56.           }
  57.         }
  58.  
  59.  
  60.  
  61.             for (int printRow = 0; printRow < num; printRow++)
  62.             {
  63.                 for (int printCol = 0; printCol < num; printCol++)
  64.                 {
  65.                     Console.Write("{0,4} ", spiralMatrix[printRow, printCol]);
  66.                 }
  67.                 Console.WriteLine();
  68.             }
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement