博客
关于我
螺旋矩阵-ii(数组)
阅读量:366 次
发布时间:2019-03-04

本文共 939 字,大约阅读时间需要 3 分钟。

题目描述

给定一个整数n,将数字1到n^2n

2
按螺旋的顺序填入n×n的矩阵
例如:
给出的n=3,
你应该返回如下矩阵:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

class Solution {   public:    /**     *      * @param n int整型      * @return int整型vector
<>> */ vector
> generateMatrix(int n) { // write code here vector
> matrix(n, vector
(n)); int left = 0; int right = n-1; int up = 0; int down = n-1; int index = 1; while(left <= right && up <= down){ for(int i = left; i <= right && up <= down; i++){ matrix[up][i] = index; index++; } for(int i = up+1; i <= down && left<= right; i++){ matrix[i][right] = index++; } for(int i = right-1; i >= left && up <= down; i--){ matrix[down][i] = index++; } for(int i = down-1; i >= up+1 && left <= right; i--){ matrix[i][left] = index++; } left++; right--; up++; down--; } return matrix; }};

在这里插入图片描述

错因分析

  • 我前面都是创建的(n+1)*(n+1)维的数组,导致答案一直出错

转载地址:http://eydg.baihongyu.com/

你可能感兴趣的文章
N!
查看>>
N-Gram的基本原理
查看>>
n1 c语言程序,全国青少年软件编程等级考试C语言经典程序题10道七
查看>>
Nacos Client常用配置
查看>>
nacos config
查看>>
Nacos Config--服务配置
查看>>
Nacos Derby 远程命令执行漏洞(QVD-2024-26473)
查看>>
Nacos 与 Eureka、Zookeeper 和 Consul 等其他注册中心的区别
查看>>
Nacos 单机集群搭建及常用生产环境配置 | Spring Cloud 3
查看>>
Nacos 启动报错[db-load-error]load jdbc.properties error
查看>>
Nacos 报Statement cancelled due to timeout or client request
查看>>
Nacos 注册服务源码分析
查看>>
Nacos 融合 Spring Cloud,成为注册配置中心
查看>>
Nacos-注册中心
查看>>
Nacos-配置中心
查看>>
Nacos2.X 源码分析:为订阅方推送、服务健康检查、集群数据同步、grpc客户端服务端初始化
查看>>
Nacos2.X 配置中心源码分析:客户端如何拉取配置、服务端配置发布客户端监听机制
查看>>
Nacos2.X源码分析:服务注册、服务发现流程
查看>>
NacosClient客户端搭建,微服务注册进nacos
查看>>
Nacos中使用ribbon
查看>>