Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class ReverseSpiralMatrix
- {
- static void Main()
- {
- Console.Write("Enter a positive whole number in the range [1 ... 31], for N = ");
- string numberStr = Console.ReadLine();
- int numN = int.Parse(numberStr);
- if (numN < 1 || numN > 31)
- {
- Console.WriteLine("Error - The number is Out of Range !!!");
- }
- else
- {
- int[,] matrix = new int[numN, numN];
- int row = 0;
- int col = 0;
- string direction = "right";
- int maxValue = numN * numN;
- for (int i = maxValue; i >= 1; i--)
- {
- if (direction == "right" && (col > (numN - 1) || matrix [row, col] != 0))
- {
- direction = "down";
- row++;
- col--;
- }
- if (direction == "down" && (row > (numN - 1) || matrix [row, col] != 0))
- {
- direction = "left";
- row--;
- col--;
- }
- if (direction == "left" && (col < 0 || matrix [row, col] != 0))
- {
- direction = "up";
- row--;
- col++;
- }
- if (direction == "up" && (row < 0 || matrix[row, col] != 0))
- {
- direction = "right";
- row++;
- col++;
- }
- matrix [row, col] = i;
- if (direction == "right")
- {
- col++;
- }
- if (direction == "down")
- {
- row++;
- }
- if (direction == "left")
- {
- col--;
- }
- if (direction == "up")
- {
- row--;
- }
- }
- // Print the numbers in reverse order to spiral matrix:
- Console.WriteLine("The numbers in Reverse Spiral Matrix are:");
- for (int r = 0; r < numN; r++)
- {
- for (int c = 0; c < numN; c++)
- {
- Console.Write("{0,4} ", matrix [r, c]);
- }
- Console.WriteLine();
- }
- }
- Console.ReadLine();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement