Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace SpiralMatrix
- {
- class Program
- {
- static void Main(string[] args)
- {
- int size = int.Parse(Console.ReadLine());
- int[,] matrix = new int[size, size];
- int index = 0;
- int x = 0;
- int square = (size * size);
- bool move = true;
- while (move)
- {
- ToRight(size, matrix, index, ref x, square, ref move);
- ToBottom(size, matrix, index, ref x, square, ref move);
- ToLeft(size, matrix, index, ref x, square, ref move);
- ToUp(size, matrix, index, ref x, square, ref move);
- index++;
- }
- Print(size, matrix);
- }
- private static void ToUp(int size, int[,] matrix, int idx, ref int x, int sq, ref bool move)
- {
- for (int col = idx; col < idx + 1; col++)
- {
- for (int row = size - 2 - idx; row > idx; row--)
- {
- x++;
- matrix[row, col] = x;
- if (x == sq)
- {
- move = false;
- break;
- }
- }
- }
- }
- private static void ToLeft(int size, int[,] matrix, int idx, ref int x, int sq, ref bool move)
- {
- for (int row = size - 1 - idx; row > size - 2 - idx; row--)
- {
- for (int col = size - 2 - idx; col >= 0 + idx; col--)
- {
- x++;
- matrix[row, col] = x;
- if (x == sq)
- {
- move = false;
- break;
- }
- }
- }
- }
- private static void ToBottom(int size, int[,] matrix, int idx, ref int x, int sq, ref bool move)
- {
- for (int col = size - 1 - idx; col > size - 2 - idx; col--)
- {
- for (int row = 1 + idx; row < size - idx; row++)
- {
- x++;
- matrix[row, col] = x;
- if (x == sq)
- {
- move = false;
- break;
- }
- }
- }
- }
- private static void ToRight(int size, int[,] matrix, int idx, ref int x, int sq, ref bool move)
- {
- for (int row = idx; row < idx + 1; row++)
- {
- for (int col = idx; col < size - idx; col++)
- {
- x++;
- matrix[row, col] = x;
- if (x == sq)
- {
- move = false;
- break;
- }
- }
- }
- }
- private static void Print(int size, int[,] matrix)
- {
- for (int row = 0; row < size; row++)
- {
- for (int col = 0; col < size; col++)
- {
- Console.Write(matrix[row, col] + " ");
- }
- Console.WriteLine();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment