leetcode 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 ]
]

中文理解:

给定一个整数n,给出n*n方阵,同时方阵的元素排列按照顺时针按层递增顺序。

解题思路:

按照层不断递增进行赋值。

代码(java):

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res=new int[n][n];
        int value=1;
        int startRow=0,startCol=0,rows=n-1,cols=n-1;
        while(startRow<=rows && startCol<=cols){
            //对上横行进行赋值
            for(int i=startCol;i<=cols;i++){
                res[startRow][i]=value++;
            }
            //对右竖进行赋值
            for(int i=startRow+1;i<=rows;i++){
                res[i][cols]=value++;
            }
            //对下横进行赋值
            for(int i=cols-1;i>=startCol && startRow!=rows;i--){
                res[rows][i]=value++;
            }
            //对左竖进行赋值
            for(int i=rows-1;i>=startRow+1 && startCol!=cols;i--){
                res[i][startCol]=value++;
            }
            startRow++;startCol++;rows--;cols--;
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/leo_weile/article/details/90200541