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

Related issue Spiral Matrix

public class Solution {
    public int[][] generateMatrix(int n) {
        int mid = n/2;
        int val = 1;
        int[][] res = new int[n][n];

        for(int i=0; i<mid; i++){
            int last = n-i-1;

            for(int k = i; k<last; k++){
                res[i][k] = val++;
            }
            for(int k = i; k<last; k++){
                res[k][last] = val++;
            }
            for(int k =last; k>i;k--){
                res[last][k] = val++;
            }
            for(int k=last; k>i;k--){
                res[k][i]= val++;
            }
        }
        if(n%2 == 1) res[n/2][n/2] = val;
        return res;
    }
}

results matching ""

    No results matching ""