首页 > 其他 > 详细

59. Spiral Matrix II

时间:2016-05-09 06:53:09      阅读:177      评论:0      收藏:0      [点我收藏+]
    /*
     * 59. Spiral Matrix II 
     * 12.5 by Mingyang
     * 注意,这里我们说的Matrix就是正方形,不再是长方形了,所以我们会用
     * 更简单的方法,就是直接上下左右分别加1就好了,最后再判断是否有中间那个
     * 不用向I一样在里面判断是否是需要判断while里面只有一行或者一列
     */
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int k = 1;
        int top = 0, bottom = n - 1, left = 0, right = n - 1;
        while (left < right && top < bottom) {
            for (int j = left; j < right; j++) {
                res[top][j] = k++;
            }
            for (int i = top; i < bottom; i++) {
                res[i][right] = k++;
            }
            for (int j = right; j > left; j--) {
                res[bottom][j] = k++;
            }
            for (int i = bottom; i > top; i--) {
                res[i][left] = k++;
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        if (n % 2 != 0)
            res[n / 2][n / 2] = k;
        return res;
    }

 

59. Spiral Matrix II

原文:http://www.cnblogs.com/zmyvszk/p/5472480.html

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