LeetCode 59 旋转矩阵II -- 模拟
2022/1/10 6:05:41
本文主要是介绍LeetCode 59 旋转矩阵II -- 模拟,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix-ii
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
提示:
1 <= n <= 20
参考文章:这个循环可以转懵很多人!
思路:
本题是模拟题,突破点在于将每一步操作的区域视为一个左闭右开的区间,如下图
这样基本写起来就没什么问题。设当前圈的起始位置为(x,x),每转一圈后,新的一圈的起始位置为(x+1, x+1)。
本题Java代码:
class Solution { public int[][] generateMatrix(int n) { int[][] ans=new int[n][n]; int start=0;//起始位置 int loop=n/2;//绕圈次数 int count=1;//计数 while(loop--!=0){ //从左到右 for(int i=start;i<n-1-start;i++){ ans[start][i]=count++; } //从上到下 for(int i=start;i<n-1-start;i++){ ans[i][n-1-start]=count++; } //从右到左 for(int i=n-1-start;i>start;i--){ ans[n-1-start][i]=count++; } //从下到上 for(int i=n-1-start;i>start;i--){ ans[i][start]=count++; } start++; } if(n%2==1)ans[start][start]=count;//当n为奇数时注意对中间的数字进行赋值 return ans; } }
这篇关于LeetCode 59 旋转矩阵II -- 模拟的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-05feign默认connecttimeout和readtimeout是多少-icode9专业技术文章分享
- 2024-07-05idea控制台,日志太多,导致部分想看得日志被刷走 搜不到-icode9专业技术文章分享
- 2024-07-05The server selected protocol version Tls10 is not accepted by client preferences [TLs12]-icode9专业技术文章分享
- 2024-07-05怎么清理项目缓存-icode9专业技术文章分享
- 2024-07-04安装 Eyoucms详细图文教程-icode9专业技术文章分享
- 2024-07-04ueditor 复制文章时,图片的链接是一个下载图片地址,该如何处理?-icode9专业技术文章分享
- 2024-07-04怎样判断host有没有对wordpress有缓存呢-icode9专业技术文章分享
- 2024-07-04具有编译功能的系统make后,无法ssh连接-icode9专业技术文章分享
- 2024-07-04make后如何升级ssh-icode9专业技术文章分享
- 2024-07-03微信支付提示下单账户与支付账户不一致-icode9专业技术文章分享