首页 > 其他 > 详细

spiral-matrix-ii 生成顺时针序列

时间:2018-09-13 00:20:55      阅读:187      评论:0      收藏:0      [点我收藏+]

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

For example,
Given n =3,

You should return the following matrix:

[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
注意左->右可遍历全,剩余两个方向遍历时需+1,最后一个方向掐头去尾避免重复遍历
class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        vector<vector<int>> result(n,vector<int>(n));
         
        if(n==0)
            return result;
         
        int step = 1;
         
        int left = 0; int right = n-1; int top = 0; int bottom = n-1;
        while(left<=right && top<=bottom)
        {
            // 左->右
            for(int i=left;i<=right;i++) {
                result[top][i] = step;
                step++;
            }
            //上->下
            for(int i=top+1;i<=bottom;i++) {
                result[i][right] = step;
                step++;
            }
            //右->左
            for(int i=right-1;i>=left;i--) {
                result[bottom][i] = step;
                step++;
            }
            //下->上
            for(int i=bottom-1;i>top;i--) {
                result[i][left] = step;
                step++;
            }
             
            left++; right--; top++; bottom--;
        }
        return result;
    }
};

 

spiral-matrix-ii 生成顺时针序列

原文:https://www.cnblogs.com/zl1991/p/9638226.html

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