we traverse the matrix as the spiral order. Each loop we go through the four edges of the periphery of the remaining matrix. The number of the periphery is n/2 and the number of elements in each edge of the peripehry is n-1-2*i

Thus we can have the code:

public class Solution {
    public int[][] generateMatrix(int n) {
        if(n < 0) n = 0 - n;
        int[][] matrix = new int[n][n];
        if(n == 0) return matrix;
        int count = 0;
        for(int i = 0; i < n/2; i++){
            int num = n-1-i*2;
            for(int j = 0; j < num; j++){
                matrix[i][i+j] = count+j+1;
                matrix[i+j][i+num] = count+num+j+1;
                matrix[i+num][i+num-j] = count+2*num+j+1;
                matrix[i+num-j][i] = count+3*num+j+1;
            }
            count += 4*num;
        }
        if(n%2 == 1) matrix[n/2][n/2] = n*n;
        return matrix;
    }
}

  

 

posted on 2016-01-19 12:41  爱推理的骑士  阅读(158)  评论(0)    收藏  举报