Advertisement
Guest User

Homework: Loops Problem 19. Spiral Matrix

a guest
Aug 17th, 2014
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.56 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[,] spiral = new int[n, n];
  9.         int count = 1;
  10.         int row = 0;
  11.         int col = -1;
  12.  
  13.         for (int k = 0; k <= n / 2; k++)
  14.         {
  15.             //right
  16.             for (col = col + 1; col <= n - 1 - k; col++)
  17.             {
  18.                 spiral[row, col] = count;
  19.                 if (count == n * n)
  20.                     goto print;
  21.                 count++;
  22.             }
  23.             col--;
  24.  
  25.             //down
  26.             for (row = row + 1; row <= n - 1 - k; row++)
  27.             {
  28.                 spiral[row, col] = count;
  29.                 if (count == n * n)
  30.                     goto print;
  31.                 count++;
  32.             }
  33.             row--;
  34.  
  35.             //left
  36.             for (col = col - 1; col >= k; col--)
  37.             {
  38.                 spiral[row, col] = count;
  39.                 if (count == n * n)
  40.                     goto print;
  41.  
  42.                 count++;
  43.             }
  44.             col++;
  45.  
  46.             //up
  47.  
  48.             for (row = row - 1; row > k; row--)
  49.             {
  50.                 spiral[row, col] = count;
  51.                 if (count == n * n)
  52.                     goto print;
  53.  
  54.                 count++;
  55.             }
  56.             row++;
  57.         }
  58.   print:
  59.         for (row = 0; row < n; row++)
  60.         {
  61.             for (col = 0; col < n; col++)
  62.             {
  63.                 Console.Write("{0,4}", spiral[row, col]);
  64.             }
  65.             Console.WriteLine();
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement