• 【LeetCode】59. Spiral Matrix II


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

    Spiral Matrix实现基本一致,只不过上题是遍历输出,这题是遍历输入。

    由于这题保证是方阵,因此不用考虑Spiral Matrix中重复扫描行/列的问题。

    class Solution {
    public:
        vector<vector<int> > generateMatrix(int n) {
            int layer = (n+1)/2;
            vector<vector<int> > ret(n, vector<int>(n, 0));
            int num = 1;
            for(int i = 0; i < layer; i ++)
            {
                //top-left --> top-right
                for(int j = i; j < n-i; j ++)
                    ret[i][j] = num ++;
                //top-right --> bottom-right
                for(int j = i+1; j < n-i; j ++)
                    ret[j][n-1-i] = num ++;
                //bottom-right --> bottom-left
                for(int j = n-1-i-1; j >= i; j --)
                    ret[n-1-i][j] = num ++;
                //bottom-left --> top-left
                for(int j = n-1-i-1; j > i; j --)
                    ret[j][i] = num ++;
            }
            return ret;
        }
    };

  • 相关阅读:
    openstack-1基础环境准备
    ELK补充之Filebeat
    ELK补充之logstash
    ELK
    dubbo
    zokeeper+kafka
    rabbitmq
    jenkins补充-编写自动化脚本实现devops 流水线和回滚等操作
    sonar
    python连接数据库之(连接MySQL)
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4157415.html
Copyright © 2020-2023  润新知