博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
剑指Offer SnakeNumber 蛇形填数
阅读量:4208 次
发布时间:2019-05-26

本文共 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/

你可能感兴趣的文章
Linux下软件安装:Openblas安装
查看>>
C++中的friend详细解析
查看>>
c++11 完美转发 std::forward()
查看>>
c++ 布置new
查看>>
c++ sizeof和alignof区别
查看>>
c++ std::aligned_storage
查看>>
c++ std::is_copy_constructible
查看>>
c++ typeid函数
查看>>
python中的上下文管理协议 __enter__ __exit__
查看>>
python里面的list转换成ctypes里面的向量
查看>>
c++ 通过宏生成静态的变量
查看>>
Ubuntu16.05+CUDA9.0下编译OpenCV错误 [...cuda_compile_generated_gpu_mat.cu.o] Error 1
查看>>
ubuntu安装opencv3.2.0
查看>>
numpy 使用delete根据index删除array里面的数据
查看>>
RPN 具体实现细节
查看>>
Mac CLion配置OpenCV环境
查看>>
cmake 常用命令,生成可执行文件
查看>>
线性可分感知机
查看>>
逻辑回归
查看>>
背包问题,动态规划
查看>>