[LeetCode]59. Spiral Matrix II

旋转矩阵打印

Posted by JinFei on March 9, 2020

题目描述

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

Example:

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

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n, vector<int>(n));
        int num = 1;
        int cycle = (min(n, n) - 1) / 2 + 1;
        for(int i = 0; i < cycle; i++){
            for(int j = i; j < n - i; j++){
                res[i][j] = num++;
            }
            for(int j = i + 1; j < n - i; j++){
                res[j][n - i - 1] = num++;
            }
            for(int j = n - i - 2; j >= i && n - i - 1 != i; j--){
                res[n - i - 1][j] = num++;
            }
            for(int j = n - i - 2; j > i && n - j - 1 != i; j--){
                res[j][i] = num++;
            }
        }
        return res;
    }
};