Adam's blog
Published by Adam

[Leetcode]59.螺旋矩阵Ⅱ

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

Solution:

蛇形环绕,为了减少判断或者循环的代码,我们需要环绕一圈不变的变量作为参照量。

于是!我们设置一个变量i,这个i的意思表示第i外层。

一圈的填数如下:

从左到右,从i行i列->i行n-i-1列

从上到下,从i+1行n-i-1列->n-i-1行n-i-1列

从右到左,从n-i-1行n-i-2列->n-i-1行i列

从下到上,从n-i-2行i列->i+1行i列

同时我们设置一个变量count,用于计数保证循环结束。

class Solution {
public:
  vector<vector<int>> generateMatrix(int n) { 
      vector<vector<int>> ans(n,vector<int>(n));
      int count = 1,i=0;
      while(count<=n*n){
        int j = i;
        while(j<n-i)
          ans[i][j++] = count++;
        j = i+1;
        while(j<n-i)
          ans[j++][n - i-1] = count++;
        j = n - i-2;
        while(j>i)
          ans[n -i-1][j--] = count++;
        j = n-i-1;
        while(j>=i+1)
          ans[j--][i] = count++;
        i++;
    }
    return ans;
};
posted @ 2019-03-14 22:47  AdamWong  阅读(152)  评论(0编辑  收藏  举报