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

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

    AC code:

    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            vector<vector<int>> ans(n, vector<int>(n, 0));
            int top = 0, bottom = n-1;
            int left = 0, right = n-1;
            int num = 1;
            while (top <= bottom && left <= right) {
                // left -> right
                for (int i = left; i <= right; ++i) {
                    ans[top][i] = num++;
                }
                top++;
                // top -> bottom
                for (int i = top; i <= bottom; ++i) {
                    ans[i][right] = num++;
                }
                right--;
                // right -> left
                for (int i = right; i >= left; --i) {
                    ans[bottom][i] = num++;
                }
                bottom--;
                // bottom -> top
                for (int i = bottom; i >= top; --i) {
                    ans[i][left] = num++;
                }
                left++;
            }
            return ans;
        }
    };
    
    Runtime: 0 ms, faster than 100.00% of C++ online submissions for Spiral Matrix II.
    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    axios基础用法
    CSS盒子模型
    前端跨域问题解决方案
    跨域-iframe
    swagger UI配置
    React安装和启动
    React 学习笔记
    redis学习笔记
    10个排序算法,待更新
    docker常用命令,持续更新。。。
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9818801.html
Copyright © 2011-2022 走看看