当前位置: 首页 > news >正文

【LeeCode】59.螺旋矩阵II

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

示例:

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

解:

class Solution {public int[][] generateMatrix(int n) {int[][] arr = new int[n][n]; // 创建 n * n 数组
​int topRow = 0, bottomRow = n - 1; // 定义上边界和下边界int leftCol = 0, rightCol = n - 1; // 定义左边界和右边界int direction = 0; // 初始方向,0代表向右
​int num = 1; // 要赋的值
​while (topRow <= bottomRow && leftCol <= rightCol) {if (direction == 0) { // 向右for (int i = leftCol; i <= rightCol; i++) {arr[topRow][i] = num++;}topRow++; // 上边界下移} else if (direction == 1) { // 向下for (int i = topRow; i <= bottomRow; i++) {arr[i][rightCol] = num++;}rightCol--; // 右边界左移} else if (direction == 2) { // 向左for (int i = rightCol; i >= leftCol; i--) {arr[bottomRow][i] = num++;}bottomRow--; // 下边界上移} else if (direction == 3) { // 向上for (int i = bottomRow; i >= topRow; i--) {arr[i][leftCol] = num++;}leftCol++; // 左边界右移}direction = (direction + 1) % 4; // 切换方向}return arr;}
}

另解:

class Solution {public int[][] generateMatrix(int n) {int loop = 0;  // 控制循环次数int[][] res = new int[n][n];int start = 0;  // 每次循环的开始点(start, start)int count = 1;  // 定义填充数字int i, j;
​while (loop++ < n / 2) { // 判断边界后,loop从1开始// 模拟上侧从左到右for (j = start; j < n - loop; j++) {res[start][j] = count++;}
​// 模拟右侧从上到下for (i = start; i < n - loop; i++) {res[i][j] = count++;}
​// 模拟下侧从右到左for (; j >= loop; j--) {res[i][j] = count++;}
​// 模拟左侧从下到上for (; i >= loop; i--) {res[i][j] = count++;}start++;}
​if (n % 2 == 1) {res[start][start] = count;}
​return res;}
}

http://www.lryc.cn/news/246078.html

相关文章:

  • rsyslog学习
  • Navicat 技术指引 | GaussDB服务器对象的创建/设计(编辑)
  • 有哪些可信的SSL证书颁发机构?
  • MidJourney笔记(4)-settings
  • 前端开发学习 (三) 列表功能
  • win11渗透武器库,囊括所有渗透工具
  • 13-21-普通数组、矩阵
  • 代码随想录算法训练营第四十六天【动态规划part08】 | 139.单词拆分、背包总结
  • go语言基础 break和contine区别
  • vue3父子组件通过$parent与ref通信
  • PHP中的常见的超全局变量
  • leetcode9.回文数
  • springboot(ssm大学生二手电子产品交易平台 跳蚤市场系统Java(codeLW)
  • 关于微信小程序中如何实现数据可视化-echarts动态渲染
  • 在Windows WSL (Linux的Windows子系统)上运行的Ubuntu如何更改主机名
  • 如何使用内网穿透将Tomcat网页发布到公共互联网上【内网穿透】
  • 网络入门---网络的大致了解
  • 构建沉浸式 AI 文本编辑器:开源 3B 编辑器的设计原则与思路
  • 【从删库到跑路 | MySQL总结篇】表的增删查改(进阶上)
  • [每周一更]-(第74期):Docker-compose 部署Jenkins容器-英文版及错误纠错
  • MySQL日期函数sysdate()与now()的区别,获取当前时间,日期相关函数
  • 邦芒解析:面试怎么谈自身优缺点
  • 【libGDX】加载G3DJ模型
  • 0基础学习VR全景平台篇第123篇:VR视频航拍补天 - PR软件教程
  • webpack打包三方库直接在html里面使用
  • Redis使用increment方法返回null的原因以及解决方案
  • springMVC,什么是Spring MVC? Spring MVC的主要组件? springMVC工作原理/流程 MVC框架
  • 【论文阅读】TACAN:控制器局域网中通过隐蔽通道的发送器认证
  • C语言第三十五弹---打印九九乘法表
  • 线性代数的艺术