• LeetCode(59)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 ]
    ]

    分析

    与54题Spiral Matrix相似题,为一个二维矩阵进行螺旋状赋值

    AC代码

    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            vector<vector<int> > ret(n,vector<int>(n , 0));
            if (n <= 0)
                return ret;
    
            int index = 1 , row = n-1 , col = n-1;
            for (int x = 0, y = 0; x <= row && y <= col; x++, y++)
            {
                //为矩阵首行赋值
                for (int j = y; j <= col; ++j , index++)
                    ret[x][j] = index;
    
                //为矩阵最右列赋值
                for (int i = x + 1; i <= row; ++i,index++)
                    ret[i][col] = index;
    
                //为矩阵最底行赋值
                for (int j = col - 1; j >= y && x != row; --j, index++)
                    ret[row][j] = index;
    
                //为矩阵最左列赋值
                for (int i = row - 1; i > x && y != col; --i, index++)
                    ret[i][y] = index;
    
                //为内旋子矩阵赋值
                row--;
                col--;
    
            }//for
            return ret;
        }
    };
    

    GitHub测试程序源码

  • 相关阅读:
    Hive的架构和工作流程
    Hive的定义及搭建
    HBase API操作
    HBase相关概念简介
    HBase shell常用命令
    HBase的简介和搭建
    scrapy useragent
    scrapy settings
    scrapy中的request对象
    python语法
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214880.html
Copyright © 2020-2023  润新知