码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Spiral Matrix II

时间:2018-05-20 10:49:51      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:ini   pre   int   led   gen   ==   上下   order   ase   


Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]


本题就是按照螺旋的顺序把数字依次塞进去,我们可以维护上下左右边界的四个变量,一圈一圈往里面添加。最后要注意的是,如果n是奇数,要把中心那个点算上。

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        //initialize four top corner
        int left = 0;
        int right = n-1;
        int bottom = n-1;
        int top = 0;
        int num = 1;
        
        while (left < right && top < bottom){
            //left -> right
            for(int i=left; i<right; i++){
                res[top][i] = num++;
            }
            //top -> bottom
            for(int i=top; i<bottom; i++){
                res[i][right] = num++;
            }
            //right -> left
            for (int i = right; i>left; i--){
                res[bottom][i] = num++;
            }
            //bootom -> top
            for(int i = bottom; i>top; i--){
                res[i][left] = num++;
            }
            left++;
            right--;
            bottom--;
            top++;
            
        }
        if(n % 2 == 1){
            res[n/2][n/2] = num;
        }
        return res;
    }
}

 

LeetCode - Spiral Matrix II

标签:ini   pre   int   led   gen   ==   上下   order   ase   

原文地址:https://www.cnblogs.com/incrediblechangshuo/p/9062339.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!