Advertisement
vlad0

Loops - Spiral Matrix

Dec 7th, 2012
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.70 KB | None | 0 0
  1. using System;
  2.  
  3. class MatrixSpiral
  4. {
  5.     static void Main(string[] args)
  6.     {
  7.         int size = 0;
  8.         bool successParse;
  9.         do
  10.         {
  11.             Console.Write("Enter the rows/cols of the matrix: ");
  12.             successParse = int.TryParse(Console.ReadLine(), out size);
  13.         } while (!successParse);
  14.  
  15.         int[,] matrix = new int[size, size];
  16.         int count = 1;
  17.         int startRow = 0;
  18.         int startCol = 0;
  19.         int endRow = size - 1;
  20.         int endCol = size - 1;
  21.  
  22.         do
  23.         {
  24.             //move right
  25.             for (int cols = startCol; cols <= endCol; cols++)
  26.             {
  27.                 matrix[startRow, cols] = count;
  28.                 count++;
  29.             }
  30.  
  31.             startRow = startRow + 1;
  32.  
  33.  
  34.             //move down
  35.             for (int i = startRow; i <= endRow; i++)
  36.             {
  37.                 matrix[i, endCol] = count;
  38.                 count++;
  39.             }
  40.  
  41.             endCol = endCol - 1;
  42.  
  43.  
  44.             //move left
  45.             for (int i = endCol; i >= startCol; i--)
  46.             {
  47.                 matrix[endRow, i] = count;
  48.                 count++;
  49.             }
  50.  
  51.             endRow = endRow - 1;
  52.             //move up
  53.             for (int i = endRow; i >= startRow; i--)
  54.             {
  55.                 matrix[i, startCol] = count;
  56.                 count++;
  57.             }
  58.  
  59.             startCol = startCol + 1;
  60.         } while (size * size >= count);
  61.  
  62.         //print matrix
  63.         for (int i = 0; i < size; i++)
  64.         {
  65.             for (int j = 0; j < size; j++)
  66.             {
  67.                 Console.Write("{0,4}", matrix[i, j]);
  68.             }
  69.  
  70.             Console.WriteLine();
  71.         }
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement