static void Main(string[] args)
{
Console.Write("请输入正整数:");
int n = int.Parse(Console.ReadLine()); //读取输入
Console.WriteLine();
int[,] arr = GetSpiralMatrix(n);
//输出矩阵
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(arr[j, i]);
Console.Write("\t"); //对齐
}
Console.Write("\n");
}
Console.ReadKey();
}
/// <summary>
/// 获取螺旋矩阵输出的方法
/// </summary>
static int[,] GetSpiralMatrix(int row)
{
int[,] intArr = new int[row, row];
int x = 0, y = 0; //初始坐标
int m = 1; //初始圈数
string type = "R"; //初始方向为右
for (int i = 1; i <= row * row; i++)
{
intArr[x, y] = i; //初始值
switch (type)
{
case "R": //向右
x++;
if (y == 0) { type = "D"; m++; break; }
if (i == m * m - m) { type = "U"; break; }
break;
case "D": //向下
y++;
if (x == 0) { type = "R"; m++; break;}
if (i == m * m - m) { type = "L"; break;}
break;
case "L": //向左
x--;
if (i == m * m - 1) { type = "D"; break; }
break;
case "U": //向上
y--;
if (i == m * m - 1) { type = "R"; break; }
break;
}
}
return intArr;
}
另一种样式的螺旋数组输出
最新推荐文章于 2024-11-12 10:17:03 发布