【leetcode】59. Spiral Matrix II 方阵向内循环

1. 题目

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

2. 思路

是之前的Spiral Matrix的简化版本,https://segmentfault.com/a/11…

3. 代码

class Solution {
public:
    // 一圈圈的转,每次转最外面的一圈。
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> matrix;
        for (int i = 0; i < n; i++) {
            matrix.push_back(vector<int>());
            vector<int>& r = matrix.back();
            for (int j = 0; j < n; j++) {
                r.push_back(0);
            }
        }
        int ki = 0;
        int kj = 0; // 左上顶点的坐标
        if (n == 0) {return matrix;}
        int cnt = 1;
        while (ki < (n+1)/2) {
            // 最后单点
            if (kj == n-kj-1) {
                for (int i = ki; i < n-ki; i++) {
                    matrix[i][n-kj-1] = cnt++;
                }
                return matrix;
            }
            
            // 上行[ki, kj] -> [ki, n-kj-1]
            for (int j = kj; j < n-kj-1; j++) {
                matrix[ki][j] = cnt++;
            }
            // 右竖[ki, n-kj-1] -> [m-ki-1, n-kj-1]
            for (int i = ki; i < n-ki-1; i++) {
                matrix[i][n-kj-1] = cnt++;
            }
            // 下行[m-ki-1, kj] <- [m-ki-1, n-kj-1]
            for (int j = n-kj-1; j > kj; j--) {
                matrix[n-ki-1][j] = cnt++;
            }
            // 左竖[ki, kj] <- [m-ki-1, kj]
            for (int i = n-ki-1; i > ki; i--) {
                matrix[i][kj] = cnt++;
            }
            ki++;
            kj++;
        }
        return matrix;
    }
};
    原文作者:knzeus
    原文地址: https://segmentfault.com/a/1190000007365544
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞