所以我正在使用 C# 创建一个螺旋矩阵。
螺旋阵列是前 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();
}
}
}
非常感谢任何帮助!