• [LC] 59. Spiral Matrix II



    Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

    Example:

    Input: 3
    Output:
    [
     [ 1, 2, 3 ],
     [ 8, 9, 4 ],
     [ 7, 6, 5 ]
    ]

    class Solution {
        public int[][] generateMatrix(int n) {
            int[][] matrix = new int[n][n];
            int beginRow = 0, endRow = n - 1;
            int beginCol = 0, endCol = n - 1;
            int num = 1;
            while(beginRow <= endRow && beginCol <= endCol) {
                for(int i = beginCol; i <= endCol; i++) {
                    matrix[beginRow][i] = num;
                    num += 1;
                }
                beginRow += 1;
                
                for (int i = beginRow; i <= endRow; i++) {
                    matrix[i][endCol] = num;
                    num += 1;
                }
                endCol -= 1;
                // no need to check boarder b/c it is square
                for (int i = endCol; i >= beginCol; i--) {
                    matrix[endRow][i] = num;
                    num += 1;
                }
                endRow -= 1;
                
                for (int i = endRow; i >= beginRow; i--) {
                    matrix[i][beginCol] = num;
                    num += 1;
                }
                beginCol += 1;
            }
            return matrix;
        }
    }


  • 相关阅读:
    css变量
    es6的this指向
    Java面试题(包装类)
    moment笔记
    Class
    CSS斜切角
    Element.getBoundingClientRect()
    Do not mutate vuex store state outside mutation handlers.
    antd不想写那么多option怎么办
    解析URL参数
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12131328.html
Copyright © 2020-2023  润新知