Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class SpiralArray
- {
- /*Използваме двумерен масив (таблица на повече от един ред, индексация и на колоните и на редовете)*/
- static void Main()
- {
- Console.Write("Enter a number:\nN = ");
- int number = int.Parse(Console.ReadLine());
- // Инициализираме нов масив
- int[,] spiral = new int[number,number];
- string direction = "right";
- int currentRow = 0;
- int currentCol = 0;
- //текущия елемент
- for (int i = 1; i <= number*number; i++)
- {
- // смяна на посоката
- if (direction == "right" && (currentCol >= number || spiral[currentRow, currentCol] != 0)) //с проверка за попълнено поле
- {
- currentCol--;
- currentRow++;
- direction = "down";
- }
- else if (direction == "down" && (currentRow >= number || spiral[currentRow, currentCol] != 0))
- {
- currentCol--;
- currentRow--;
- direction = "left";
- }
- else if (direction == "left" && (currentCol < 0 || spiral[currentRow, currentCol] != 0))
- {
- currentCol++;
- currentRow--;
- direction = "up";
- }
- else if (direction == "up" && (currentRow < 0 || spiral[currentRow, currentCol] != 0))
- {
- currentCol++;
- currentRow++;
- direction = "right";
- }
- //Движение по клетките
- spiral[currentRow, currentCol] = i;
- if (direction == "right")
- {
- currentCol++;
- }
- else if (direction == "down")
- {
- currentRow++;
- }
- else if (direction == "left")
- {
- currentCol--;
- }
- else if (direction == "up")
- {
- currentRow--;
- }
- }
- //print matrix
- for (int i = 0; i < number; i++)
- {
- for (int j = 0; j < number; j++)
- {
- Console.Write(spiral[i,j] + " ");
- }
- Console.WriteLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment