Advertisement
SSkrev

SpiralMatrix

Mar 24th, 2014
585
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.87 KB | None | 0 0
  1. using System;
  2.  
  3. class SpiralMatrix
  4. {
  5.     static void Main()
  6.     {
  7.        Console.Write("n=");
  8.         int n = int.Parse(Console.ReadLine());
  9.         int i = 0;
  10.         int j = 0;
  11.         char dir = 'r';
  12.         if (n >= 1 && n <= 100)
  13.         {
  14.             int[,] mass = new int[n,n];
  15.             for (int st = 1; st <= n*n; st++)
  16.             {
  17.                 if (dir == 'r' && (j > n - 1 || mass[i, j] != 0))
  18.                 {
  19.                     dir = 'd';
  20.                     j--;
  21.                     i++;              
  22.                 }
  23.                 if (dir == 'd' && (i > n - 1 || mass[i, j] != 0))
  24.                 {
  25.                     dir = 'l';
  26.                     i--;
  27.                     j--;
  28.                 }
  29.                 if (dir == 'l' && (j < 0 || mass[i, j] != 0))
  30.                 {
  31.                     dir = 'u';
  32.                     j++;
  33.                     i--;                
  34.                 }
  35.                 if (dir == 'u' && (i < 0 || mass[i, j] != 0))
  36.                 {
  37.                     dir = 'r';
  38.                     i++;
  39.                     j++;
  40.                 }
  41.                 mass[i, j] = st;
  42.  
  43.                 switch (dir)
  44.                 {
  45.                     case 'u': i--;
  46.                         break;
  47.                     case 'd': i++;
  48.                         break;
  49.                     case 'l': j--;
  50.                         break;
  51.                     case 'r': j++;
  52.                         break;
  53.                 }
  54.  
  55.             }
  56.             for (int r = 0; r < n; r++)
  57.             {
  58.                 for (int c = 0; c < n; c++)
  59.                 {
  60.                     Console.Write("{0,2}", mass[r, c]);
  61.                 }
  62.                 Console.WriteLine();            
  63.             }      
  64.         }
  65.         else
  66.         {
  67.             Console.WriteLine("Error. Bad input!");
  68.         }
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement