当前位置:网站首页>59、螺旋矩阵(数组)
59、螺旋矩阵(数组)
2022-04-23 10:12:00 【Popuessing's Jersey】
题目:
给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
public int[][] generateMatrix(int n){
//创建一个二维数组
int [][] res = new int[n][n];
//定义每循环一圈的起始位置
int startX =0,startY=0;
//每个圈循环几次,例如n为奇数3,那么loop=3/2=1,只是循环一圈,矩阵中间的只需要单独处理
int loop = n/2;
//矩阵中间的位置,例如:n为3,中间的位置就是[1,1];
int mid = n/2;
//用来给矩阵中每一个空格赋值
int count =1;
//每一圈循环,需要控制每一条边遍历的长度
int offset =1;
int i,j;
while(loop >0){
i = startX;
j = startY;
//下面开始的四个for就是模拟转一圈
//模拟填充上行从左到右(左闭右开)
for (j = startY; j <startY+n-offset ; j++) {
res[startX][j] = count++;
}
//模拟填充右列从上到下(左闭右开)
for (i = startX; i <startX+n-offset ; i++) {
res[i][j] = count++;
}
//模拟填充下行从右到左(左闭右开)
for (; j>startY;j--){
res[i][j] = count++;
}
//模拟填充左列从下到上(左闭右开)
for (; i>startX;i--){
res[i][j] = count++;
}
//第二圈开始的时候,起始位置要各自加1,
startX++;
startY++;
//offset控制每一圈里每一条边遍历的长度
offset+=2;
loop--;
}
//如果n为奇数,需要单独给矩阵最中间的位置赋值
if(n%2==1){
res[mid][mid] = count;
}
return res;
}
public static void main(String[] args) {
Luoxuanjuzhen luoxuanjuzhen = new Luoxuanjuzhen();
int [][]res = luoxuanjuzhen.generateMatrix(4);
for (int [] x:res) {
for (int y:x) {
System.out.print(y+" ");
}
}
}
输出结果:
1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7
时间复杂度:O(n)
版权声明
本文为[Popuessing's Jersey]所创,转载请带上原文链接,感谢
https://blog.csdn.net/CoCo629vanilla/article/details/121385713
边栏推荐
- 基于PyQt5实现弹出任务进度条功能示例
- JVM——》常用参数
- 一文读懂PlatoFarm新经济模型以及生态进展
- Sim Api User Guide(7)
- SQL tuning series - SQL performance methodology
- DBA common SQL statements (5) - latch related
- 2022年制冷与空调设备运行操作考试练习题及模拟考试
- DBA common SQL statements (1) - overview information
- 通过流式数据集成实现数据价值(1)
- Realize data value through streaming data integration (1)
猜你喜欢

Sim Api User Guide(4)

Read LSTM (long short term memory)

Sim Api User Guide(6)

Solve the problem of installing VMware after uninstalling

Exercise questions and simulation test of refrigeration and air conditioning equipment operation test in 2022

NEC红外遥控编码说明

计算机网络安全实验二|DNS协议漏洞利用实验

Arm debugging (1): two methods to redirect printf to serial port in keil

Zhengda international explains what the Dow Jones industrial index is?

Juc并发编程09——Condition实现源码分析
随机推荐
Go language practice mode - functional options pattern
《谷雨系列》空投
Turn: Maugham: reading is a portable refuge
杰理之栈溢出 stackoverflow 怎么办?【篇】
The central control learning infrared remote control module supports network and serial port control
Chapter II in memory architecture (im-2.2)
Pyqt5与通信
MapReduce核心和基础Demo
Sim Api User Guide(8)
LeetCode-608. 树节点
解决VMware卸载后再安装出现的问题
Exercise questions and simulation test of refrigeration and air conditioning equipment operation test in 2022
Redis design and Implementation
Chapter 3 enable and adjust the size of IM column storage (im-3.1)
Depth selector
LeetCode-608. Tree node
1、两数之和(哈希表)
Formattime timestamp format conversion
Yarn核心参数配置
Go语言实践模式 - 函数选项模式(Functional Options Pattern)