zoukankan      html  css  js  c++  java
  • 【LeetCode】Spiral Matrix II

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

    For example,
    Given n = 3,

    You should return the following matrix:

    [
     [ 1, 2, 3 ],
     [ 8, 9, 4 ],
     [ 7, 6, 5 ]
    ]
    此题与Spiral Matrix类似,可以用相同的方法解决,相比之下,此题比前一题简单
    public class Solution {
        public int[][] generateMatrix(int n) {
            int[][] matrix=new int[n][n];
            int temprow=n;
            int tempcol=n;
            int start =-1;
            int end=-1;
            int t=1;
            while(temprow>0&&tempcol>0){
                start++;
                end++;
                for(int i=start;i<tempcol;i++){
                    matrix[start][i]=t;
                    t++;
                }
                    
                for(int j=start+1;j<temprow;j++){
                    matrix[j][tempcol-1]=t;
                    t++;
                }
                for(int x=tempcol-2;x>=end;x--){
                    matrix[temprow-1][x]=t;
                    t++;
                }
                    
                for(int y=temprow-2;y>start;y--){
                    matrix[y][end]=t;
                    t++;
                }
                    
                
                temprow=temprow-1;
                tempcol=tempcol-1;
            }
            return matrix;
            
        }
    }
  • 相关阅读:
    (2/24) 快速上手一个webpack的demo
    (1/24) 认识webpack
    module.exports 、exports、export、export default的区别
    Git同时提交到多个远程仓库
    @codeforces
    @loj
    @bzoj
    @loj
    @bzoj
    @bzoj
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3722211.html
Copyright © 2011-2022 走看看