本文共 1601 字,大约阅读时间需要 5 分钟。
题目描述:
在n*n的方阵里填入1,2..,n*n 要求填成蛇形例如n=4时方阵为:
10 11 12 19 16 13 28 15 14 37 6 5 4
思路:
首先蛇形填入数据,可以把操作分为四个步骤:从上往下,从右往左,从下往上,从左往右。 定义x,y表示元素在矩阵中的横纵坐标,首先循环从上往下给数组赋值,纵坐标y不变 横坐标x递增,直到横坐标达到矩阵的边界n-1结束。之后是从右往左打印,横坐标不变,纵坐标递减到矩阵边界即0为止。之后从下往上,纵坐标不变,横坐标递减到0.再从左往右,此时的循环出口条件就不是到矩阵边界了,因为最左上角的元素在第一轮操作就已经赋值了,这个时候我们想到初始化矩阵数组时,默认为数组的每个元素赋值为0,因此我们可以考虑添加出口条件就是当前元素的后一个元素不为0时,证明该元素已经在之前被符号值 我们直接跳出循环改变方向即可public static int[][] fillSnakeNumber(int n) { int[][] matrix = new int[n][n];//定义方阵 默认初始化每个元素为0 int x, y;//表示方阵的横纵下标 int count = matrix[x = 0][y = n - 1] = 1;//表示当前数值 while (count < n * n) { //先从上往下 while (x + 1 < n && matrix[x + 1][y] == 0) { matrix[++x][y] = ++count; } //再从右往左 while (y - 1 >= 0 && matrix[x][y - 1] == 0) { matrix[x][--y] = ++count; } //从下往上 while (x - 1 >= 0 && matrix[x - 1][y] == 0) { matrix[--x][y] = ++count; } //从左往右 while (y + 1 < n && matrix[x][y + 1] == 0) { matrix[x][++y] = ++count; } } return matrix; }
测试数据:
@Test public void testFillSnakeNumber() throws Exception { int[][] ints = SnakeNumber.fillSnakeNumber(4); for (int i = 0; i < ints.length; i++) { for (int j = 0; j < ints[i].length; j++) { System.out.print(ints[i][j]+" "); } System.out.println(); } }
输出结果
10 11 12 1 9 16 13 2 8 15 14 3 7 6 5 4
转载地址:http://khqli.baihongyu.com/