[牛客网-Leetcode] #数组 简单 spiral-matrix-ii

螺旋矩阵ii spiral-matrix-ii

题目描述

给定一个整数n,将数字1到n^2n
2
按螺旋的顺序填入n×n的矩阵
例如:
给出的n=3,
你应该返回如下矩阵:
[↵ [ 1, 2, 3 ],↵ [ 8, 9, 4 ],↵ [ 7, 6, 5 ]↵]

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

示例

输入

2

输出

[[1,2],[4,3]]

解题思路

  • 将螺旋矩阵看成一个个同心矩阵,从外往内一层一层地按照顺时针顺序遍历。
  • 设定四个边界:left,right,top,bottom,初始分别为0,n - 1,0,n - 1
  • 每一个同心矩阵的四个边界范围(从上面那条边开始)分别是left ~ right, top + 1 ~ bottom, right - 1 ~ left, bottom + 1~top - 1
  • 每遍历完一个同心矩阵,left++, right- -, top- -, bottom++
class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        vector<vector<int> > result(n, vector<int>(n));
        if(n < 1) return result;
        //四个边界
        int left(0), right(n - 1), top(0), bottom(n - 1);
        //用于不断累加计数,填入螺旋矩阵
        int cnt(1);
        while(left <= right && top <= bottom) {
            //填充上边界
            for(int i = left; i <= right; i ++) {
                result[top][i] = cnt ++;
            }
            //填充右边界
            for(int i = top + 1; i <= bottom; i ++) {
                result[i][right] = cnt ++;
            }
            //填充下边界
            for(int i = right - 1; i >= left; i --) {
                result[bottom][i] = cnt ++;
            }
            //填充左边界
            for(int i = bottom - 1; i >= top + 1; i --) {
                result[i][left] = cnt ++;
            }
            //修改四个边界,继续填充下一层同心矩阵
            left ++; right --; top ++; bottom --;
        }
        
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值