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;
        }
    
    }
    

      

  • 相关阅读:
    no space left on device
    功能测试用例
    数据库命令
    移动APP测试用例设计实践经验(转载)
    15个常用sql命令
    将Windows文件夹挂载到Linux上
    英语学习方法
    三种特质 做领导
    扬州之行 第一天
    list、dict、str虽然是Iterable,却不是Iterator
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11338387.html
Copyright © 2011-2022 走看看