Advertisement
dim4o

Loops_19_SpiralMatrix

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