螺旋形打印矩阵

来源:互联网 发布:eve人物捏脸数据 编辑:程序博客网 时间:2024/05/29 15:22

代码是从网上copy来的,但是自己理解了一下,并且重新修改了一下,本来他是逆时针打印的,现在我改成顺时针打印,挺好理解的。

这里用到的就是int[,]而不是int[][],据说int[,]只有在c#里面有,到现在还不知道具体怎么区分这两个之间的区别。

 

 int[,] array = new int[6, 6]{

              {11,12,13,14,15, 16},

              {21,22,23,24,25, 26},

              {31,32,33,34,35,36},

              {41,42,43,44,45,46},

              {51,52,53,54,55,56},

              {61,62,63,64,65,66}

            };

 

            int x = 0;

            int y = 0;

            int length = array.GetLength(0);

            for (int i = 0; i < length / 2; i++)

            {

                // 注意数组[y,x],其中y为第几行,x为第几列,也就是说y增加是下移,x增加是右移

                x = y = i;

                while (x < length - 1 - i)

                {

                    Console.WriteLine(array[y, x++]);

                }

                while (y < length - 1 - i)

                {

                    Console.WriteLine(array[y++, x]);

                }

                while (x > i)

                {

                    Console.WriteLine(array[y, x--]);

                }

                while (y > i)

                {

                    Console.WriteLine(array[y--, x]);

                }

            }

            if (length % 2 == 1)

            {

                int center = length / 2 ;

                Console.WriteLine(array[center,center]);

            }

 

            Console.Read();

原创粉丝点击