Advertisement
vasko1926

19. Spiral Matrix

Jan 13th, 2015
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 1.71 KB | None | 0 0
  1. using System;
  2.  
  3. class SpiralMatrix
  4. {
  5.     static void Main()
  6.     {
  7.         int n = int.Parse(Console.ReadLine());
  8.         int maxN = (int)Math.Pow(n, 2);
  9.         int[,] matrix = new int[n, n];
  10.         int row = 0;
  11.         int col = 0;
  12.         string direction = "right";
  13.  
  14.         for (int i = 1; i <= maxN; i++)
  15.         {
  16.             if (direction == "right" && (col > n - 1 || matrix[row, col] != 0))
  17.             {
  18.                 direction = "down";
  19.                 col--;
  20.                 row++;
  21.             }
  22.             if (direction == "down" && (row > n - 1 || matrix[row, col] != 0))
  23.             {
  24.                 direction = "left";
  25.                 row--;
  26.                 col--;
  27.             }
  28.             if (direction == "left" && (col < 0 || matrix[row, col] != 0))
  29.             {
  30.                 direction = "up";
  31.                 col++;
  32.                 row--;
  33.             }
  34.             if (direction == "up" && row < 0 || matrix[row, col] != 0)
  35.             {
  36.                 direction = "right";
  37.                 row++;
  38.                 col++;
  39.             }
  40.  
  41.             matrix[row, col] = i;
  42.  
  43.             if (direction == "right")
  44.             {
  45.                 col++;
  46.             }
  47.             if (direction == "down")
  48.             {
  49.                 row++;
  50.             }
  51.             if (direction == "left")
  52.             {
  53.                 col--;
  54.             }
  55.             if (direction == "up")
  56.             {
  57.                 row--;
  58.             }
  59.         }
  60.         for (int j = 0; j < n; j++)
  61.         {
  62.             for (int k = 0; k < n; k++)
  63.             {
  64.                 Console.Write("{0,4}", matrix[j, k]);
  65.             }
  66.             Console.WriteLine();
  67.         }
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement