Advertisement
Guest User

Multidimensional Arrays - 1d) Spiral

a guest
Dec 30th, 2013
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.95 KB | None | 0 0
  1. using System;
  2.  
  3. class MatrixD
  4. {
  5.     static void Main()
  6.     {
  7.         Console.Write("Enter a size of the matrix: ");
  8.         int n = int.Parse(Console.ReadLine());
  9.         int[,] spiral = new int[n, n];
  10.         int currentRow = 0;
  11.         int currentColumn = 0;
  12.         string direction = "down";
  13.         for (int i = 1; i <= n*n; i++)
  14.         {
  15.             if (direction == "down" && (currentRow >= n || spiral[currentRow,currentColumn]!=0))
  16.             {
  17.                 currentRow--;
  18.                 currentColumn++;
  19.                 direction = "right";
  20.             }
  21.             else if (direction == "right" && (currentColumn >= n || spiral[currentRow,currentColumn]!=0))
  22.             {
  23.                 currentColumn--;
  24.                 currentRow++;
  25.                 direction = "up";
  26.             }
  27.             else if (direction == "up" && (currentRow > 0 || spiral[currentRow,currentColumn]!=0))
  28.             {
  29.                 currentRow--;
  30.                 currentColumn--;
  31.                 direction = "left";
  32.             }
  33.             else if (direction == "left" && (currentColumn > 0 || spiral[currentRow,currentColumn]!=0))
  34.             {
  35.                 currentColumn++;
  36.                 currentRow++;
  37.                 direction = "down";
  38.             }
  39.  
  40.             spiral[currentRow, currentColumn] = i;
  41.  
  42.             if (direction == "down")
  43.             {
  44.                 currentRow++;
  45.             }
  46.             else if (direction == "right")
  47.             {
  48.                 currentColumn++;
  49.             }
  50.             else if (direction == "up")
  51.             {
  52.                 currentRow--;
  53.             }
  54.             else if (direction == "left")
  55.             {
  56.                 currentColumn--;
  57.             }
  58.         }
  59.         for (int i=0; i<n; i++)
  60.         {
  61.             for (int j=0; j<n; j++)
  62.             {
  63.                 Console.Write(spiral[i,j]+" ");
  64.             }
  65.             Console.WriteLine();
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement