首页 > 代码库 > 面试题:打印蛇形二维数组
面试题:打印蛇形二维数组
如何这样打印一个数组:
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(); } }
面试题:打印蛇形二维数组
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。