码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-12-28 22:10:18      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

如何这样打印一个数组:

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();
            }
        }

 

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

标签:

原文地址:http://www.cnblogs.com/DotNetNuke/p/4190672.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!