小弟不才,若有高手路过,请多指点,不胜荣幸!
话说,今日参加一家公司面试,要求实现如上如这种矩阵,初一看 ,就一矩阵,信誓旦旦的以为很简单呢,结果开始写代码的时候才发现这不是一般的矩阵,而是一只蜗牛呀,直接昏倒!老实说,小弟当时被这只蜗牛吓到了,然后果断放弃了,答了剩下的题。至于面试结果如何,且听有机会的时候分解!
面试受挫,但我不能停止前进的脚步,归来之后仔细研究了一下,发现了如下 规律:
如此图所示,最外层的规律便是红线所示的四组数组成的,哈 ,既然发现了规律 ,那么繁琐的工作就交给计算机来完成了,那么,我就先咽下第一口芥末喽:
Step1:实现红线1
首先,做些准备工作吧
1: int num=0;
2: Console.WriteLine("请输入矩阵的长度:");
3: string getKeys= Console.ReadLine();
4: int.TryParse(getKeys, out num); //输入数组长度
5: int[,] dataArray =new int[num,num];
6: int y=0; //设置初始值,线一开始位置 坐标 x,y
7: int x=0;
8: int number=1; //蜗牛的起点
线1的实现就很简单了,简单的一个循环
1:
2: int startX = x;
3: int startY = y;
4: while (y < num-1)
5: {
6: dataArray[startX, y] = number;
7: number++;
8: y++;
9: }
Step2:实现整个外围
后面的坐标变化,还是直接上图吧:
既然知道了坐标是怎么变化的,那么就通过一些列的循环赋值吧!
1: int startX = x;
2: int startY = y;
3: while (y < num-1)
4: {
5: dataArray[startX, y] = number;
6: number++;
7: y++;
8: }
9: while (x < num - 1)
10: {
11: dataArray[x, y] = number;
12: number++;
13: x++;
14: }
15:
16: while (y > startX)
17: {
18:
19: dataArray[x, y] = number;
20: number++;
21: y--;
22: }
23: while (x > y)
24: {
25: dataArray[x, y] = number;
26: number++;
27: x--;
28: }
Step3:还你一颗真诚的心!
哈 ,原来内部也是有规律的 ,这个时候,是不是要递归一下呢?
1: private static int First(int num, int[,] dataArray, int y, int x, int number)
2: {
3:
4: int startX = x;
5: int startY = y;
6: #region 实现蜗牛的围墙
7: while (y < num - 1)
8: {
9: dataArray[startX, y] = number;
10: number++;
11: y++;
12: }
13: while (x < num - 1)
14: {
15: dataArray[x, y] = number;
16: number++;
17: x++;
18: }
19:
20: while (y > startX)
21: {
22:
23: dataArray[x, y] = number;
24: number++;
25: y--;
26: }
27: while (x > y)
28: {
29: dataArray[x, y] = number;
30: number++;
31: x--;
32: }
33: #endregion
34: num -= 1;
35: startX++;
36: startY++;
37: if (num > 2)
38: {
39: return First(num, dataArray, startY, startX, number);
40: }
41: else
42: {
43: return 0;
44: }
45: }
如果,我输入的是一个奇数呢?
此处只贴代码了
if (num % 2 != 0)// 判断矩阵长度是否为奇数
{
dataArray[num / 2, num / 2] = num * num;
}