Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class SpiralMatrix
- {
- static void Main()
- {
- Console.Write("x = ");
- int x = int.Parse(Console.ReadLine());
- Console.Write("y = ");
- int y = int.Parse(Console.ReadLine());
- Console.WriteLine();
- int[,] arrInt = new int[y, x];
- /* Generate matrix [x,y] */
- for (int a = 0; a < y; a++)
- {
- for (int b = 0; b < x; b++)
- {
- arrInt[a, b] = x * a + b + 1;
- }
- }
- /* Print matrix [x,y] */
- for (int a = 0; a < y; a++)
- {
- for (int b = 0; b < x; b++)
- {
- Console.Write("{0,5}", arrInt[a, b]);
- }
- Console.WriteLine();
- }
- Console.WriteLine();
- /* Print matrix in spiral form */
- byte direction = 0; /*0-right, 1-down, 2-left, 3-right*/
- int row = 0, col = 0;
- int matrixIndex = 0;
- for (int k = 0; k < y; k++)
- {
- for (int c = 0; c < x; c++)
- {
- Console.Write(arrInt[row, col] + " ");
- if (direction == 0) //right
- {
- if (col + 1 + matrixIndex >= x)
- {
- direction = 1;
- row++;
- }
- else
- {
- col++;
- }
- }
- else if (direction == 1) //down
- {
- if (row + 1 + matrixIndex >= y)
- {
- direction = 2;
- col--;
- }
- else
- {
- row++;
- }
- }
- else if (direction == 2) //left
- {
- if (col - 1 - matrixIndex < 0)
- {
- direction = 3;
- row--;
- }
- else
- {
- col--;
- }
- }
- else if (direction == 3) //up
- {
- if (matrixIndex + 1 == row)
- {
- matrixIndex++;
- }
- if (row - 1 - matrixIndex < 0)
- {
- direction = 0;
- col++;
- }
- else
- {
- row--;
- }
- }
- }
- }
- Console.WriteLine();
- Console.WriteLine();
- Console.ReadLine();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement