Advertisement
anilak

Corrected Spiral Matrix

Nov 29th, 2013
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.56 KB | None | 0 0
  1. using System;
  2.  
  3. class Program
  4. {
  5.     static void Main()
  6.     {
  7.         Console.WriteLine("enter n");
  8.             int n = int.Parse(Console.ReadLine());
  9.             int[,] spiral = new int[n, n];
  10.             int c =1;
  11.             int rows = 0;
  12.             int cols = 0;
  13.             int t = 0;
  14.  
  15.             while (c <= n*n)
  16.             {
  17.                 while ((rows <= n - 1 - t))  //right
  18.                 {
  19.                     spiral[cols, rows] = c;
  20.                     c++;
  21.                     rows++;
  22.                 }
  23.                 rows--;
  24.                 cols++;
  25.                 while (cols <= n - 1 - t)  //down
  26.                 {
  27.                     spiral[cols, rows] = c;
  28.                     c++;
  29.                     cols++;
  30.                 }
  31.                 cols--;
  32.                 rows--;
  33.                 while ((rows >= t))  //left
  34.                 {
  35.                     spiral[cols, rows] = c;
  36.                     c++;
  37.                     rows--;
  38.                 }
  39.                 rows++;
  40.                 cols--;
  41.                 while (cols >= 1 + t)  //up
  42.                 {
  43.                     spiral[cols, rows] = c;
  44.                     c++;
  45.                     cols--;
  46.                 }
  47.                 cols++;
  48.                 rows++;
  49.             t++;
  50.             }
  51.             for (int i = 0; i < n; i++)
  52.             {
  53.                 for (int j = 0; j < n; j++)
  54.                 {
  55.                     Console.Write("{0}\t",spiral[i, j]);
  56.                 }
  57.                 Console.WriteLine();
  58.             }
  59.         }
  60.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement