zoukankan      html  css  js  c++  java
  • Leetcode:59. Spiral Matrix II

    Description

    Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.

    Example

    Given n = 3,
    
    You should return the following matrix:
    [
        [ 1, 2, 3 ],
        [ 8, 9, 4 ],
        [ 7, 6, 5 ]
    ]
    

    思路

    • 没啥好说的,一圈一圈的打印

    代码

    cclass Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            vector<vector<int>> res(n, vector<int>(n, 0));
            
            int start = 0;
            int sum = 1;
            while(start * 2 < n){
               generate(res, n, start, sum);
               start++;
            }
            
            return res;
        }
        
        void generate(vector<vector<int>>& res, int n, int start, int &count){
            int endCol = n - start - 1;
            int endRow = n - start - 1;
                    
            for(int i = start; i <= endCol; ++i)
                res[start][i] = count++;
                    
            if(endRow > start){
                for(int i = start + 1; i <= endRow; ++i)
                    res[i][endCol] = count++;
            }
                    
            if(endCol > start){
                for(int i = endCol - 1; i >= start; --i)
                    res[endRow][i] = count++;
            }
                    
            if(endRow > start && endCol > start){
                for(int i = endRow - 1; i > start; --i)
                    res[i][start] = count++;
            }
        }
    };
    
  • 相关阅读:
    Java工具类
    集合 -- 嵌套表
    集合--索引表
    第一章
    记录Record
    序列Sequence
    操纵数据库 DML
    表的集合操作
    视图
    索引
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6876128.html
Copyright © 2011-2022 走看看