1. 程式人生 > >LeetCode | Spiral Matrix II(螺旋矩陣填充資料)

LeetCode | Spiral Matrix II(螺旋矩陣填充資料)

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為奇數的時候,需要額外處理。只要細心就行了、

class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        vector<vector<int> > res;
        for(int i = 0;i < n;i++){
            vector<int> tmp = vector<int>(n,0);
            res.push_back(tmp);
        }
        int count = 1;
        for(int i = 0;i < n/2;i++){
            for(int j = i;j < n-i-1;j++)
                res[i][j] = count++;
            for(int j = i;j < n-i-1;j++)
                res[j][n-i-1] = count++;
            for(int j = n-i-1;j > i;j--)
                res[n-1-i][j] = count++;
            for(int j = n-i-1;j > i;j--)
                res[j][i] = count++;
        }
        if(n%2)
            res[n/2][n/2] = count;
        return res;
    }
};