Venciity

[ Telerik C#] LOOPS - EX 14 Spiral Matrix

Feb 13th, 2014
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.24 KB | None | 0 0
  1. // * Write a program that reads a positive integer number N (N < 20)
  2. //   from console and outputs in the console the numbers 1 ... N numbers arranged as a spiral.
  3.  
  4. using System;
  5.  
  6. namespace ex14___SpiralMatrix
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             Console.Write("Enter N: ");
  13.             int n =Int32.Parse(Console.ReadLine());
  14.             int[,] matrix = new int[n, n];
  15.             int row = 0;
  16.             int col = 0;
  17.             string direction = "right";
  18.             int maxRotations = n * n;
  19.  
  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.                     col--;
  32.                     row--;
  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.                     col++;
  44.                     row++;
  45.                 }
  46.  
  47.                 matrix[row, col] = i;
  48.                 if (direction == "right")
  49.                 {
  50.                     col++;
  51.                 }
  52.                 if (direction == "down")
  53.                 {
  54.                     row++;
  55.                 }
  56.                 if (direction == "left")
  57.                 {
  58.                     col--;
  59.                 }
  60.                 if (direction == "up")
  61.                 {
  62.                     row--;
  63.                 }
  64.             }
  65.  
  66.             // Display Matrix
  67.  
  68.             for (int r = 0; r < n; r++)
  69.             {
  70.                 for (int c = 0; c < n; c++)
  71.                 {
  72.                     Console.Write("{0,4}", matrix[r,c]);
  73.                 }
  74.                 Console.WriteLine();
  75.             }
  76.         }
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment