顺时针螺旋递减等差数列矩阵

由用户输入一个整数(>=1),则形成一个顺时针螺旋递减等差数列矩阵,
符合1,2,3…n*n
输入数字2,则程序输出:
1 2
4 3
输入数字3,则程序输出:
1 2 3
8 9 4
7 6 5
输入数字4, 则程序输出:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

static void Main(string[] args) { Console.Write("Please input n:"); int n = Convert.ToInt32(Console.ReadLine()); int[,] arr=new int[n,n]; int x = 0; int y = 0; string direction = "right"; for (int i = 1; i <= n * n;i++ ) { switch (direction) { case "right": arr[x, y++] = i; if (y == n || arr[x, y] != 0)//如果当前列索引为n(到了最右), 或当前元素右边的元素不为0, 转下 { direction = "bottom"; y--; x++; } break; case "bottom": arr[x++, y] = i; if (x == n || arr[x, y] != 0)//如果当前行索引为n(到了最下), 或当前元素下边的元素不为0, 转左 { direction = "left"; x--; y--; } break; case "left": arr[x, y--] = i; if (y == -1 || arr[x, y] != 0)//如果当前列索引为-1(到了最左), 或当前元素左边的元素不为0, 转上 { direction = "top"; y++; x--; } break; case "top": arr[x--, y] = i; if (arr[x, y] != 0)//如果上面的一行不为0, 转右 { direction = "right"; x++; y++; } break; } } for (int i = 0; i < arr.GetLength(0); i++) { for (int j = 0; j < arr.GetLength(1); j++) { Console.Write(arr[i,j]+"/t"); } Console.WriteLine(); } Console.ReadLine(); }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值