1. 程式人生 > >LeetCode 59 Spiral Matrix II 螺旋矩陣之二

LeetCode 59 Spiral Matrix II 螺旋矩陣之二

log mce -m 什麽 -- owin pre with body

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

此題跟之前那道本質上沒什麽區別,就相當於個類似逆運算的過程,這道題是要按螺旋的順序來填數,由於給定矩形是個正方形,我們計算環數時用n / 2來計算,若n為奇數時,註意一下中間點。

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
         
        vector<vector<int>> v(n,vector<int>(n,1));
        int cnt = 1;
        int p=n; 
        for (int i=0; i<n/2; i++, p=p-2){
            for(int col=i; col < i+p; col ++){
                v[i][col] 
= cnt++; } for(int row=i+1; row < i+p; row++){ v[row][i+p-1] = cnt++; } for(int col=i+p-2; col>=i; col--){ v[i+p-1][col] = cnt++; } for(int row=i+p-2; row>i; row--){ v[row][i]
= cnt++; } } if((n%2) == 1)v[n/2][n/2] = cnt; return v; } };

LeetCode 59 Spiral Matrix II 螺旋矩陣之二