Advertisement
psotirov

Spiral Matrix of Numbers

Dec 6th, 2012
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.32 KB | None | 0 0
  1. using System;
  2.  
  3. class SpiralMatrix
  4. {
  5.     enum Direction { right, down, left, up }
  6.  
  7.     static void Main()
  8.     {
  9.         int N = 0;
  10.  
  11.         Console.Write("Please enter the dimension of a matrix N: ");
  12.         if (!int.TryParse(Console.ReadLine(), out N) || N < 2 || N > 19) return;
  13.  
  14.         if (N > 12) Console.BufferWidth = Console.WindowWidth = N*6+5; // resize the console windows if needed
  15.  
  16.         int[,] matrix = new int[N, N]; //creates array that represents the NxN matrix
  17.         int row = 0; // initial cell coordinates
  18.         int col = 0;
  19.         Direction dir = Direction.right; // intital direction is to the right
  20.  
  21.         for (int i = 1; i <= N*N; i++) // Iterates through the all values that must be put into cells
  22.         {
  23.             matrix[row, col] = i; // put the value into cureent cell
  24.             switch (dir) // moves to the next cell and checks for boundary (end of matrix or non empty cell)
  25.             {
  26.                 case Direction.right:
  27.                     col++;
  28.                     if (col == (N-1) || matrix[row, col+1] > 0) dir = Direction.down;
  29.                     break;
  30.                 case Direction.down:
  31.                     row++;
  32.                     if (row == (N-1) || matrix[row+1, col] > 0) dir = Direction.left;
  33.                     break;
  34.                 case Direction.left:
  35.                     col--;
  36.                     if (col == 0 || matrix[row, col-1] > 0) dir = Direction.up;
  37.                     break;
  38.                 case Direction.up:
  39.                     row--;
  40.                     if (row == 0 || matrix[row-1, col] > 0) dir = Direction.right;
  41.                     break;
  42.                 default:
  43.                     break;
  44.             }
  45.         }
  46.  
  47.         string separator = "+";
  48.         for (int i = 0; i < N; i++)
  49.             separator = separator + "-----+"; // creates horizontal border
  50.  
  51.         Console.WriteLine(separator);
  52.         for (int r = 0; r < N; r++) // outputs the matrix
  53.         {
  54.             Console.Write("|"); // starting vertical border
  55.             for (int c = 0; c < N; c++)
  56.             {
  57.                 Console.Write(" {0,3} |", matrix[r, c]); // prints formatted cell with intermedite separator / closing vertical border
  58.             }
  59.             Console.WriteLine("\n" + separator); // last horizontal border
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement