首页 > 其他 > 详细

Jan 18 - Spiral Matrix II; 2D Array;

时间:2016-01-19 14:03:18      阅读:250      评论:0      收藏:0      [点我收藏+]

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;
    }
}

  

 

Jan 18 - Spiral Matrix II; 2D Array;

原文:http://www.cnblogs.com/5683yue/p/5141862.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!