Leetcode——数组:螺旋矩阵59.螺旋矩阵
题目
思路
对于每层,从左上方开始以顺时针的顺序填入所有元素。假设当前层的左上角位于 (top,left),右下角位于 (bottom,right),按照如下顺序填入当前层的元素。
从左到右填入上侧元素,依次为 (top,left) 到 (top,right)。
从上到下填入右侧元素,依次为 (top+1,right) 到 (bottom,right)。
如果 left<right 且 top<bottom,则从右到左填入下侧元素,依次为 (bottom,right−1) 到 (bottom,left+1),以及从下到上填入左侧元素,依次为 (bottom,left) 到 (top+1,left)。
填完当前层的元素之后,将 left 和 top 分别增加 1,将 right 和 bottom 分别减少 1,进入下一层继续填入元素,直到填完所有元素为止。
代码
class Solution {
public:vector<vector<int>> generateMatrix(int n) {int num = 1;vector<vector<int>> matrix(n, vector<int>(n));int left = 0, right = n - 1, top = 0, bottom = n - 1;while (left <= right && top <= bottom) {for (int column = left; column <= right; column++) //列是从左边开始,向右移动{matrix[top][column] = num; //给矩阵赋值num++; //矩阵值增加}for (int row = top + 1; row <= bottom; row++) { //行从第一行开始,向下增加matrix[row][right] = num; //继续增加,给矩阵赋值num++;}if (left < right && top < bottom) {for (int column = right - 1; column > left; column--) {matrix[bottom][column] = num;num++;}for (int row = bottom; row > top; row--) {matrix[row][left] = num;num++;}}left++;right--;top++;bottom--;}return matrix;}
};