[leetcode] 59. Spiral Matrix II 解题报告

题目链接:https://leetcode.com/problems/spiral-matrix-ii/

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

For example,
Given n = 3,

You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

思路:和 Spiral Matrixs思路一样,同样是设置行进向量,在碰到边界的时候改变一下向量的方向和左右上下边界。

代码如下:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<int> tem(n);
        vector<vector<int>> result(n, tem);
        if(n <= 0) return result;
        int flagX = 1, flagY = 0, cnt = n*n, i =1, x =0, y =0;
        int left = 0, right = n-1, top = 0, bottom = n-1;
        while(i <= cnt)
        {
            result[y][x] = i;
            if(x >= right && flagX == 1)//碰到右边界,则最上边的一行遍历完了,改变上边界
            {
                flagX = 0;
                flagY = 1;
                top++;
            }
            else if(y >= bottom && flagY == 1)//碰到下边界,则最右边的一行遍历完了,改变右边界
            {
                flagX = -1;
                flagY = 0;
                right--;
            }
            else if(x <= left && flagX == -1)//碰到左边界,则最下边的一行遍历完了,改变下边界
            {
                flagX = 0;
                flagY = -1;
                bottom--;
            }
            else if(y <= top && flagY == -1)//碰到上边界,则最左边的一行遍历完了,改变左边界
            {
                flagX = 1;
                flagY = 0;
                left++;
            }
            x += flagX;
            y += flagY;
            i++;
        }
        return result;
    }

};


你可能感兴趣的:(LeetCode,算法,array)