Advertisement
Guest User

Spiral Matrix

a guest
Mar 23rd, 2014
429
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.88 KB | None | 0 0
  1. static void Main()
  2.         {
  3.             System.Console.SetWindowSize(100, 30);
  4.             int n = int.Parse(Console.ReadLine());
  5.             int[,] matrix = new int[n, n];
  6.             int row = 0;
  7.             int col = 0;
  8.             int value = 1;
  9.             if (n > 0 && n < 21)
  10.             {
  11.                 while (value <= n * n)
  12.                 {
  13.                     while (col < matrix.GetLength(0) && matrix[col, row] == 0)
  14.                     {
  15.                         matrix[row, col++] = value;
  16.                         value++;
  17.                     }
  18.                     col--;
  19.                     row++;
  20.                     while (row < matrix.GetLength(1) && matrix[row, col] == 0)
  21.                     {
  22.                         matrix[row++, col] = value;
  23.                         value++;
  24.                     }
  25.                     row--;
  26.                     col--;
  27.                     while (col >= 0 && matrix[row, col] == 0)
  28.                     {
  29.                         matrix[row, col--] = value;
  30.                         value++;
  31.                     }
  32.                     col++;
  33.                     row--;
  34.                     while (row >= 0 && matrix[row, col] == 0)
  35.                     {
  36.                         matrix[row--, col] = value;
  37.                         value++;
  38.                     }
  39.                     col++;
  40.                     row++;
  41.                 }
  42.  
  43.                 for (int i = 0; i < matrix.GetLength(0); i++)
  44.                 {
  45.                     for (int j = 0; j < matrix.GetLength(1); j++)
  46.                     {
  47.                         Console.SetCursorPosition(j * 5, i * 2);
  48.                         Console.Write(matrix[i, j]);
  49.                     }
  50.                     Console.WriteLine();
  51.                 }
  52.             }
  53.             else
  54.             {
  55.                 Console.WriteLine("out of range");
  56.             }
  57.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement