面试题:打印蛇形二维数组

如何这样打印一个数组:

01 02 03 04 05
16 17 18 19 06
15 24 25 20 07
14 23 22 21 08
13 12 11 10 09

我的一个解答:

static void Main(string[] args)
        {
            var m = 5;
            var matrix = new int[m, m];

            var row = 0;
            var col = 0;
            matrix[row, col] = 1;

            var moveVertically = false;

            if (m <= 0)
                return;

            while (matrix[row, col] != m * m)
            {
                if (!moveVertically)
                {
                    // Detect the right cube and try to move one setp
                    if ((col + 1) < m && matrix[row, col + 1] == 0)
                    {
                        matrix[row, col + 1] = matrix[row, col] + 1;
                        col++;
                        moveVertically = false;
                        continue;
                    }

                    // Detect the left side and try to move one step
                    if ((col - 1) >= 0 && matrix[row, col - 1] == 0)
                    {
                        matrix[row, col - 1] = matrix[row, col] + 1;
                        col--;
                        moveVertically = false;
                        continue;
                    }

                    moveVertically = true;
                }

                if (moveVertically)
                {
                    // Detect up and try to move one step
                    if ((row - 1) >= 0 && matrix[row - 1, col] == 0)
                    {
                        matrix[row - 1, col] = matrix[row, col] + 1;
                        row--;
                        moveVertically = true;
                        continue;
                    }

                    // Detect the down side and try to move one step
                    if ((row + 1) < m && matrix[row + 1, col] == 0)
                    {
                        matrix[row + 1, col] = matrix[row, col] + 1;
                        row++;
                        moveVertically = true;
                        continue;
                    }

                    moveVertically = false;
                }
            }

            Print(matrix);
        }

        private static void Print(int[,] matrix)
        {
            for (var row = 0; row < matrix.GetLength(0); row++)
            {
                for (var col = 0; col < matrix.GetLength(1); col++)
                {
                    Console.Write(string.Format(" {0}", matrix[row, col].ToString("D2")));
                }
                Console.WriteLine();
            }
        }

 

posted on 2014-12-28 21:41  m2land  阅读(1352)  评论(0编辑  收藏  举报

导航