[Leetcode]59.螺旋矩陣Ⅱ

給定一個正整數 n,生成一個包含 1 到 n2 全部元素,且元素按順時針順序螺旋排列的正方形矩陣。code

示例:io

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

Solution:

蛇形環繞,爲了減小判斷或者循環的代碼,咱們須要環繞一圈不變的變量做爲參照量。class

因而!咱們設置一個變量i,這個i的意思表示第i外層。變量

一圈的填數以下:循環

從左到右,從i行i列->i行n-i-1列while

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

從右到左,從n-i-1行n-i-2列->n-i-1行i列生成

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

同時咱們設置一個變量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;
};
相關文章
相關標籤/搜索