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

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

猜你喜欢

转载自www.cnblogs.com/zl1991/p/9638226.html