Leetcode 细节实现题 Spiral Matrix II

来源:互联网 发布:mac口红哪个系列最滋润 编辑:程序博客网 时间:2024/05/16 10:54

Spiral Matrix II

 Total Accepted: 12773 Total Submissions: 41526My Submissions

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 ]]


题意:将数值 1 到n^2以螺旋顺序放到到一个方阵中
思路:
从左到右,从上到下,从右到左,从下到上按顺序遍历放数值
将矩阵的(0,0)元素看成坐标原点,向右为x轴正方向,向下为y轴正方向
用四个变量,即两个坐标(startx, starty), (endx, endy) 表示每轮遍历的矩阵的左上角和右下角的坐标
复杂度:O(n^2)

vector<vector<int> > generateMatrix(int n){vector<vector<int> > matrix(n, vector<int>(n));int startx = 0, starty = 0;int endx = n - 1, endy = n - 1;for(int k = 1; k <= n * n; ){for(int j = startx; j <= endx; ++j) matrix[starty][j] = k++;starty++;for(int i = starty; i <= endy; ++i) matrix[i][endy] = k++;endx--;for(int j = endx; j >= startx; --j) matrix[endy][j] = k++;endy--;for(int i = endy; i >= starty; --i) matrix[i][startx] = k++;startx++;}return matrix;}


0 0