螺旋矩阵
看到最近有螺旋矩阵的东东,我也来凑个热闹!
借用下别人的图片

class Program {
static void Main(string[] args) {
for(int i = 1; i <= 10; i++) {
OutputLuoXuanJuZhen(i);
Console.WriteLine();
}
Console.Read();
}
/// <summary>
/// n为第一行包含的元素个数
/// </summary>
/// <param name="n"></param>
static void OutputLuoXuanJuZhen(int n) {
int[,] array = new int[n, n];
//计算圈数
int cycles = 0;
if(n % 2 == 0) {
cycles = n / 2;
} else {
cycles = n / 2 + 1;
}
for(int i = 0; i < cycles; i++) {
SetArray(i, n, ref array);
}
int j = 0;
foreach(int el in array) {
Console.Write(string.Format("{0:000}", el) + " ");
j++;
if(j%n==0){
Console.WriteLine("");
}
}
}
static void SetArray(int rowno, int rowCou, ref int[,] array) {
int couRow, x, y;
couRow = rowCou - 2 * rowno;
//获取设置画圈圈的起始值,这个地方要注意,要观察值的变化,多写几个,再利用数学的公式算出表达式。如1+2+3+...+n=n(n+1)/2
int preInt = 4 * ((rowCou - 1) * rowno - (rowno) * (rowno - 1));
x = y = 0;
//上
for(int i = 1; i <= couRow; i++) {
preInt++;
if(i == 1) {
x = y = rowno;
} else {
y++;
}
array[x, y] = preInt;
}
//右
for(int i = 2; i <= couRow; i++) {
preInt++;
x++;
array[x, y] = preInt;
}
//下
for(int i = 2; i <= couRow; i++) {
preInt++;
y--;
array[x, y] = preInt;
}
//左
for(int i = 2; i < couRow; i++) {
preInt++;
x--;
array[x, y] = preInt;
}
}
}
思路:循环画圈圈,每个圈圈分4段,上右下左,每段的长度都是第一行元素长度-2*圈数
另:画圈圈的时候,如果x和y反过来赋值,就是反向画圈圈。
浙公网安备 33010602011771号