zoukankan      html  css  js  c++  java
  • LeetCode 59. 螺旋矩阵 II(Spiral Matrix II)

    题目描述

    给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

    示例:

    输入: 3
    输出:
    [
     [ 1, 2, 3 ],
     [ 8, 9, 4 ],
     [ 7, 6, 5 ]
    ]

    解题思路

    LeetCode54.螺旋矩阵 的思想差不多,定义左上角的行索引,然后依次从左至右、从上至下、从右至左、从下至上遍历,注意起始索引和终止索引。

    代码

     1 class Solution {
     2 public:
     3     vector<vector<int>> generateMatrix(int n) {
     4         vector<vector<int>> res(n, vector<int>(n, 0));
     5         int idx = 0, num = 1;
     6         while(idx * 2 < n){
     7             for(int col = idx; col < n - idx; col++)
     8                 res[idx][col] = num++;
     9             for(int row = idx + 1; row < n - idx; row++)
    10                 res[row][n - idx - 1] = num++;
    11             for(int col = n - idx - 2; col >= idx; col--)
    12                 res[n - idx - 1][col] = num++;
    13             for(int row = n - idx - 2; row > idx; row--)
    14                 res[row][idx] = num++;
    15             idx++;
    16         }
    17         return res;
    18     }
    19 };
  • 相关阅读:
    流 例题

    容器集合整理
    容器集合
    容器 集合知识点
    面向对象回顾
    面向对象例题
    Java常用的8大排序算法
    Java中两个动态代理
    为什么synchronized无法禁止指令重排,却能保证有序性
  • 原文地址:https://www.cnblogs.com/wmx24/p/9391094.html
Copyright © 2011-2022 走看看