archangelmihail

Spiral

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