Итак, я создаю спиральную матрицу с помощью С#.
Спиральный массив представляет собой квадратное расположение первых N ^ 2 натуральных чисел, где числа последовательно увеличиваются по мере того, как вы идете по краям массива по спирали внутрь.
Например:
Я должен сделать это с помощью алгоритма, однако мои окончательные результаты выглядят так:
Мой код ниже:
private static void FillMatrix (int[ , ] matrix, int n)
{
int positionX = 0;
int positionY = 0;
int direction = 0; // The initial direction is "right"
int stepsCount = n - 1; // stepsCount decrements after 3/2/2/2/2...
int stepPosition = 0; // 0 steps already performed
int counter = 1; // counter increments after every turn
for (int i = 1; i < n * n; i++)
{
matrix[positionY, positionX] = i;
//moving logic:
if (stepPosition < stepsCount)
{
stepPosition++;
}
else
{
counter++;
stepPosition = 1;
if (counter <= 3)
{
direction = (direction + 1) % 4;
}
else if (counter % 2 != 0 && counter >= 5 || counter == 4)
{
stepsCount = stepsCount - 1;
direction = (direction + 1) % 4;
}
}
// Move to the next cell in the current direction
switch (direction)
{
case 0:
// right
positionX++;
break;
case 1:
// down
positionY++;
break;
case 2:
// left
positionX--;
break;
case 3:
// up
positionY--;
break;
}
}
}
private static void PrintMatrix (int[ , ] matrix, int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write("{0,3}", matrix[i, j]);
}
Console.WriteLine();
}
}
static void Main(string[] args)
{
int n;
Console.WriteLine("Please enter N: ");
bool checkN = int.TryParse(Console.ReadLine(), out n);
if (checkN)
{
int[,] spiralMatrix = new int[n,n];
FillMatrix(spiralMatrix, n);
PrintMatrix(spiralMatrix, n);
}
Console.ReadKey();
}
}
}
Любая помощь высоко ценится!