首页 > 代码库 > Spiral Matrix II

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

public class Solution {
    public int[][] generateMatrix(int n) {
        int [][]a=new int[n][n];
        
        int val=0;
        for(int layer=0;layer<n/2;++layer){
            int first=layer;
            int last=n-1-layer;
            for(int i=first;i<last;++i){
                val++;
                a[first][i]=val;
            }
            for(int j=first;j<last;j++){
                val++;
                a[j][last]=val;
            }
            for(int k=last;k>first;k--){
                val++;
                a[last][k]=val;
            }
            for(int l=last;l>layer;l--){
                val++;
                a[l][first]=val;
            }
        }
        if(n%2!=0) a[n/2][n/2]=n*n;
        return a;
    }
    
}

Spiral Matrix II