Advertisement
Alekscho85

SpiralMatrix

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