Wednesday, April 27, 2016

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


public class Solution {
    public int[][] generateMatrix(int n) {
        int[][] ret = new int[n][n];
        
        int i = 0;
        int j = 0;
        
        int c = 1;
        
        while(n > 1){
            for(int k = 0; k < n-1; ++k){
                ret[i][j++] = c++;
            }
            for(int k = 0; k < n-1; ++k){
                ret[i++][j] = c++;
            }
            for(int k = 0; k < n-1; ++k){
                ret[i][j--] = c++;
            }
            for(int k = 0; k < n-1; ++k){
                ret[i--][j] = c++;
            }
            i++;
            j++;
            n -= 2;
        }
        
        if(1 == n){
            ret[i][j] = c;
        }
        
        return ret;
        
    }
}


No comments:

Post a Comment