• spiral-matrix-ii


      

    /**
    * Given an integer n, generate a square matrix filled with elements from 1 to n 2 in spiral order.
    * For example,
    * Given n =3,
    * You should return the following matrix:
    * [
    * [ 1, 2, 3 ],
    * [ 8, 9, 4 ],
    * [ 7, 6, 5 ]
    * ]
    *
    * 给定一个整数n,生成一个以螺旋顺序填充从1到n 2元素的正方形矩阵。
    * 例如,
    * 如果n=3,
    * 您应该返回以下矩阵:
    * You should return the following matrix:
    * [
    * [ 1, 2, 3 ],
    * [ 8, 9, 4 ],
    * [ 7, 6, 5 ]
    * ]
    */

    /**
     * Given an integer n, generate a square matrix filled with elements from 1 to n 2 in spiral order.
     * For example,
     * Given n =3,
     * You should return the following matrix:
     * [
     *  [ 1, 2, 3 ],
     *  [ 8, 9, 4 ],
     *  [ 7, 6, 5 ]
     * ]
     *
     * 给定一个整数n,生成一个以螺旋顺序填充从1到n 2元素的正方形矩阵。
     * 例如,
     * 如果n=3,
     * 您应该返回以下矩阵:
     * You should return the following matrix:
     * [
     *  [ 1, 2, 3 ],
     *  [ 8, 9, 4 ],
     *  [ 7, 6, 5 ]
     * ]
     */
    
    public class Main46 {
        public static void main(String[] args) {
            int n = 5;
            int[][] matrix = generateMatrix(n);
            for (int i=0;i<n;i++) {
                for (int j=0;j<n;j++) {
                    System.out.print(matrix[i][j]+"    ");
                }
                System.out.println("");
            }
        }
    
        public static int[][] generateMatrix(int n) {
            int[][] matrix = new int[n][n];
            int count = 1;
            int start = 0;
            while (count <= n*n) {
                int endX = n-1-start;   //列
                int endY = n-1-start;   //行
    
                for (int i=start;i<=endX;i++) {
                    matrix[start][i] = count;
                    count++;
                }
                for (int i=start+1;i<=endY;i++) {
                    matrix[i][endY] = count;
                    count++;
                }
                for (int i=endX-1;i>=start && endY>start;i--) {
                    matrix[endY][i] = count++;
                }
                for (int i=endY-1;i>=start+1 && endX>start;i--) {
                    matrix[i][start] = count++;
                }
                start++;
            }
            return matrix;
        }
    
    }
    

      

  • 相关阅读:
    spring事务传播机制实例讲解
    一篇关于交叉编译的文章
    Java中的泛型方法
    层序遍历打印二叉树
    寻找第K大 网易2016实习研发工程师编程题
    二叉树的非递归遍历
    二叉树 网易2016实习研发工程师编程题
    比较重量 网易2016实习研发工程师编程题
    网络地址为172.16.0.0,采用子网掩码255.255.224.0 .以下说法正确的是?
    2.7链表 回文链表
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11338387.html
Copyright © 2020-2023  润新知