1. 程式人生 > >【LeetCode】142.Spiral Matrix II

【LeetCode】142.Spiral Matrix II

題目描述(Medium)

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

題目連結

https://leetcode.com/problems/spiral-matrix-ii/description/

Example 1:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

演算法分析

從左往右,從上往下,從右往左,從下往上,生成。

提交程式碼:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int> > matrix(n, vector<int>(n));
        int begin = 0, end = n - 1;
        int num = 1;
        
        while(begin < end) {
            for (int j = begin; j < end; ++j) matrix[begin][j] = num++;
            for (int i = begin; i < end; ++i) matrix[i][end] = num++;
            for (int j = end; j > begin; --j) matrix[end][j] = num++;
            for (int i = end; i > begin; --i) matrix[i][begin] = num++;
            
            ++begin, --end;
        }
        
        if (begin == end) matrix[begin][begin] = num;
        
        return matrix;
    }
};