当前位置:网站首页>力扣之螺旋矩阵,一起旋转起来(都能看懂)
力扣之螺旋矩阵,一起旋转起来(都能看懂)
2022-06-30 12:15:00 【学无止境java】
59.螺旋矩阵II
先放题目!
力扣链接点这里
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
思路
模拟顺时针画矩阵的过程:
- 填充上行从左到右
- 填充右列从上到下
- 填充下行从右到左
- 填充左列从下到上
代码加注释
class Solution {
public int[][] generateMatrix(int n) {
//假设n=3
int loop = 0; // 控制循环次数
int[][] res = new int[n][n];
int start = 0; // 每次循环的开始点(start, start)
int count = 1; // 定义填充数字
int i, j;
// 小于n/2为循环次数,例n=3,n^2=9,n/2=1,循环一次即可
while (loop++ < n / 2) {
// 判断边界后,loop从1开始
// 模拟上侧从左到右
for (j = start; j < n - loop; j++) {
//小于n-loop为列坐标,3-1
res[start][j] = count++;
}
// 模拟右侧从上到下
for (i = start; i < n - loop; i++) {
res[i][j] = count++;
}
// 模拟下侧从右到左
for (; j >= loop; j--) {
//j=2(因为上面当j=2时,不符合条件)
res[i][j] = count++;
}
// 模拟左侧从下到上
for (; i >= loop; i--) {
//i=2
res[i][j] = count++;
}
start++;
}
if (n % 2 == 1) {
//n=3,中心还剩一个
res[start][start] = count;
}
return res;
}
}
54. 螺旋矩阵
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10 //行数和列数
-100 <= matrix[i][j] <= 100
思路
和上一题大致相同,也是四个循环
先打印最上面一行
再打印右面那一列(注意右上角的元素已经打印过了)
再打印最下面一行(注意右下角的元素打印过了)
再打印最坐面一行(注意左下角的元素打印过了)
代码加注释
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
//定义一个存储结果的变量。
List<Integer> list = new ArrayList<>();
//为空时,直接退出。
if(matrix ==null || matrix.length ==0){
return list;
}
//构造一个 m*n 的一个矩阵
int m = matrix.length; //行(这个不理解的看最下面解释)
int n = matrix[0].length; //列(这个不理解的看最下面解释)
int i =0; //层数(从外向内的层数)
int count = (Math.min(m,n)+1)/2; //统计从外向内的总层数,至少为一层
while(i<count){
//从左往右
//行不变,列逐渐增大,特被这里 n-i是为了控制他在从外到内,第几层。最外面为第0层
// j 为变化的列
for(int j = i;j<n-i;j++){
list.add(matrix[i][j]);
}
//从上往下
//行逐渐增大,列不变
// j 为变化的行
// (n-1)-i 为最右边一列
for(int j = i+1;j<m-i;j++){
list.add(matrix[j][(n-1)-i]);
}
//从右往左
//行不变,列逐渐减小
// j 为变化的列
// (n-1)-(i+1) 这里的 i + 1是为了去除最右下角那个数,
// m-1-i 指向最右边的列, j >= i 是为了保证当行为最后一行
//这里的 (m-1-i) != i 这是用来保证,是属于同一层的
for(int j= (n-1)-(i+1); j>= i && (m-1-i != i); j--){
list.add(matrix[(m-1)-i][j]);
}
//从下往上
//列不变,行逐渐减小
// j 为可变的行
//(m-1)-(i+1) 是为了去除最左上角的数
// j >= i+1,是为了保证当前行为第二行
// (n-1-i) !=i 这是用来保证,是属于同一层的。
for(int j = (m-1)-(i+1);j >= i+1 && (n-1-i) !=i; j--){
list.add(matrix[j][i]);
}
i++; //层数加一,继续向内层递进
}
//返回结果
return list;
}
}
其中
m - 1 - i
是指随着层数增加时,层数的边界所在行(即最上行和最下行的所处的行数),如果出现最上行和最下行是同一行的情况(比如:3行5列的矩阵中,第二层是1行3列的矩阵),此时按顺序打印完第二层第一行后,第一列为空,不打印,折返后如果没有(m
- 1 - i != i)这个限制,会重新打印第二层的第一行,造成结果的值变多。同理可得,n - 1 - i != i。
小知识
二维数组中matrix.length和matrix[0].length
//言简意赅,直接看例子
public class demo1 {
public static void main(String[] args) {
int[][] matrix = new int[3][4];
System.out.println(matrix.length);
System.out.println(matrix[0].length);
}
}
输出:
3 //表示二维数组的行数
4 //表示二维数组的列数
边栏推荐
- Charles打断点修改请求数据&响应数据
- Basic interview questions for Software Test Engineers (required for fresh students and test dishes) the most basic interview questions
- rpm2rpm 打包步骤
- MySQL built-in functions
- Hisilicon 3559 universal platform construction: introduction to YUV format
- Redis6 learning notes - Chapter 2 - Basic redis6 operations
- Sword finger offer 05 Replace spaces: replace each space in the string s with "%20"“
- Visual studio configures QT and implements project packaging through NSIS
- 机器学习笔记 - 自相关和偏自相关简介
- Reading the table data of Tencent documents in the applet
猜你喜欢

Joplin implements style changes

电机控制Clarke(α/β)等幅值变换推导

海思3559开发常识储备:相关名词全解

Tencent two sides: @bean and @component are used on the same class. What happens?

SuperMap 3D SDKs_Unity插件开发——连接数据服务进行SQL查询
![[QNX Hypervisor 2.2用户手册]6.2.3 Guest与外部之间通信](/img/ca/9065325ce8882d95fb24c82fb62abc.png)
[QNX Hypervisor 2.2用户手册]6.2.3 Guest与外部之间通信

How to use AI technology to optimize the independent station customer service system? Listen to the experts!

Tencent cloud Database Engineer competency certification was launched, and people from all walks of life talked about talent training problems

Hisilicon 3559 universal platform construction: introduction to YUV format
![[300+ continuous sharing of selected interview questions from large manufacturers] column on interview questions of big data operation and maintenance (II)](/img/cf/44b3983dd5d5f7b92d90d918215908.png)
[300+ continuous sharing of selected interview questions from large manufacturers] column on interview questions of big data operation and maintenance (II)
随机推荐
【 surprise】 la vitesse de téléchargement de Thunderbolt n'est pas aussi rapide que celle de la machine virtuelle
Two batches of pure milk are unqualified? Michael responded that he was conducting a large-scale screening and sampling inspection of products
Getting started with the go language is simple: go handles XML files
ECDSA signature verification in crypt
How do different types of variables compare with zero
QT MSVC installation and commissioning
腾讯二面:@Bean 与 @Component 用在同一个类上,会怎么样?
Building a database model using power designer tools
Docker安装Mysql8和sqlyong连接报错2058的解决方法[随笔记录]
SuperMap 3D SDKs_Unity插件开发——连接数据服务进行SQL查询
时空预测2-GCN_LSTM
[QNX Hypervisor 2.2用户手册]6.2.3 Guest与外部之间通信
7 lightweight and easy-to-use tools to relieve pressure and improve efficiency for developers, and help enterprises' agile cloud launch | wonderful review of techo day
全面解析免费及收费SSH工具的基本特性和总结
[target tracking] |pytracking configuring win to compile prroi_ pool. pyd
NoSQL - redis configuration and optimization
Spatiotemporal prediction 2-gcn_ LSTM
Construction de la plate - forme universelle haisi 3559: obtenir le codage après modification du cadre de données
Clipboardjs - development learning summary 1
Substrate 源码追新导读: Pallet Alliance 并入主线,