Advertisement
remote87

Spiral Matrix

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