zoukankan      html  css  js  c++  java
  • 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;
        }
    
    }
    

      

  • 相关阅读:
    fdisk 分区
    fdisk 添加逻辑分区
    centos7 bond0 双网卡配置
    查看centos7启动项
    本地yum源安装docker
    cobbler Ubuntu16.04 安装
    docker-ce-17.03.2 离线安装RPM包
    day14 生成器的进阶
    day13迭代器与生成器
    day12闭包,装饰器
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11338387.html
Copyright © 2011-2022 走看看