当前位置:网站首页>The spiral matrix of the force buckle rotates together (you can understand it)
The spiral matrix of the force buckle rotates together (you can understand it)
2022-06-30 12:49:00 【Endless learning java】
Spiral matrix of force buckle , Rotate together
59. Spiral matrix II
Let's start with the topic !
Force button link point here
Give you a positive integer n , Generate a include 1 To n2 All the elements , And the elements are arranged in a clockwise spiral order n x n square matrix matrix .
Input :n = 3
Output :[[1,2,3],[8,9,4],[7,6,5]]
Ideas
Simulate the process of drawing a matrix clockwise :
- Fill up from left to right
- Fill in the right column from top to bottom
- Fill down from right to left
- Fill in the left column from bottom to top
Code with comments
class Solution {
public int[][] generateMatrix(int n) {
// hypothesis n=3
int loop = 0; // Control the number of cycles
int[][] res = new int[n][n];
int start = 0; // Starting point of each cycle (start, start)
int count = 1; // Define padding numbers
int i, j;
// Less than n/2 Is the number of cycles , example n=3,n^2=9,n/2=1, Just cycle once
while (loop++ < n / 2) {
// After judging the boundary ,loop from 1 Start
// Simulate the upper side from left to right
for (j = start; j < n - loop; j++) {
// Less than n-loop Column coordinates ,3-1
res[start][j] = count++;
}
// Simulate the right side from top to bottom
for (i = start; i < n - loop; i++) {
res[i][j] = count++;
}
// Simulate the lower side from right to left
for (; j >= loop; j--) {
//j=2( Because the top is j=2 when , disqualification )
res[i][j] = count++;
}
// Simulate the left side from bottom to top
for (; i >= loop; i--) {
//i=2
res[i][j] = count++;
}
start++;
}
if (n % 2 == 1) {
//n=3, There is one left in the center
res[start][start] = count;
}
return res;
}
}
54. Spiral matrix
To give you one m That's ok n Columns of the matrix matrix , Please follow Clockwise spiral sequence , Returns all elements in the matrix .
Input :matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output :[1,2,3,6,9,8,7,4,5]
Tips :
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10 // Number of rows and columns
-100 <= matrix[i][j] <= 100
Ideas
Same as the previous question , It is also four cycles
Print the top line first
Then print the right column ( Notice that the elements in the upper right corner have already been printed )
Print the bottom line again ( Notice that the elements in the lower right corner have been printed )
Then print the most sitting line ( Notice that the elements in the lower left corner have been printed )
Code with comments
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
// Define a variable to store the results .
List<Integer> list = new ArrayList<>();
// It's empty time , immediate withdrawal .
if(matrix ==null || matrix.length ==0){
return list;
}
// Construct a m*n A matrix of
int m = matrix.length; // That's ok ( See the bottom explanation for this incomprehensible )
int n = matrix[0].length; // Column ( See the bottom explanation for this incomprehensible )
int i =0; // The layer number ( Layers from outside to inside )
int count = (Math.min(m,n)+1)/2; // Count the total number of floors from outside to inside , At least one floor
while(i<count){
// From left to right
// The line doesn't change , The column grows gradually , It's here n-i To control him from the outside to the inside , What layer . The outermost part is No 0 layer
// j For variable Columns
for(int j = i;j<n-i;j++){
list.add(matrix[i][j]);
}
// From the top down
// The row grows gradually , The column does not change
// j For changing lines
// (n-1)-i For the rightmost column
for(int j = i+1;j<m-i;j++){
list.add(matrix[j][(n-1)-i]);
}
// From right to left
// The line doesn't change , Column decrement
// j For variable Columns
// (n-1)-(i+1) there i + 1 To get rid of the number in the bottom right corner ,
// m-1-i Point to the rightmost column , j >= i Is to ensure that when the last line of the behavior
// there (m-1-i) != i This is to ensure that , It belongs to the same layer
for(int j= (n-1)-(i+1); j>= i && (m-1-i != i); j--){
list.add(matrix[(m-1)-i][j]);
}
// From bottom to top
// The column does not change , The rows gradually decrease
// j Is a variable line
//(m-1)-(i+1) To remove the number in the top left corner
// j >= i+1, To ensure that the second line of the current behavior
// (n-1-i) !=i This is to ensure that , It belongs to the same layer .
for(int j = (m-1)-(i+1);j >= i+1 && (n-1-i) !=i; j--){
list.add(matrix[j][i]);
}
i++; // Number of layers plus one , Continue to advance to the inner layer
}
// Return results
return list;
}
}
among
m - 1 - i
As the number of layers increases , The row of the boundary of the number of layers ( That is, the number of rows in which the most upstream and the most downstream are located ), If the top row and the bottom row are the same ( such as :3 That's ok 5 In the matrix of columns , The second level is 1 That's ok 3 Columns of the matrix ), At this time, after the first line of the second layer is printed in sequence , The first column is empty , No printing , After turn back, if there is no (m
- 1 - i != i) This restriction , The first line of the second layer will be reprinted , The resulting value becomes more . The same can be ,n - 1 - i != i.
Little knowledge
In a two-dimensional array matrix.length and matrix[0].length
// simply , Let's look at an example
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);
}
}
Output :
3 // Represents the number of rows of a two-dimensional array
4 // Represents the number of columns of a two-dimensional array
边栏推荐
- Three ways for flinksql to customize udaf
- 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
- mqtt-ros模拟发布一个自定义消息类型
- Qt中的数据库使用
- 【MySQL】MySQL的安装与配置
- ECDSA signature verification in crypt
- Google refutes rumors and gives up tensorflow. It's still alive!
- 基于ThinkPHP5封装tronapi-波场接口-PHP版本--附接口文档-20220627
- 【 surprise】 la vitesse de téléchargement de Thunderbolt n'est pas aussi rapide que celle de la machine virtuelle
- New function of SuperMap iserver11i -- release and use of legend
猜你喜欢
QT implementation dynamic navigation bar
电机控制Clarke(α/β)等幅值变换推导
Q-learning notes
Shell编程概述
排查问题的方法论(适用于任何多方合作中产生的问题排查)
60 divine vs Code plug-ins!!
Vision based robot grasping: from object localization, object pose estimation to parallel gripper grasping estimation
Commands for redis basic operations
黑马笔记---包装类,正则表达式,Arrays类
【一天学awk】数组的使用
随机推荐
Unity脚本的基础语法(1)-游戏对象的常用操作
RDS MySQL数据迁移PolarDB MySQL费用可以转过去吗?
MySql实现两个查询结果相除
Terms related to JMeter performance test and performance test passing standards
机器学习笔记 - 自相关和偏自相关简介
Redis - problèmes de cache
【一天学awk】运算符
Flink sql控制台,不识别group_concat函数吗?
【一天学awk】正则匹配
Android development interview real question advanced version (with answer analysis)
Dqn notes
【一天学awk】内置变量的使用
Layout of pyqt5 interface and loading of resource files
【一天学awk】数组的使用
[qnx hypervisor 2.2 user manual]6.2.3 communication between guest and external
Vision based robot grasping: from object localization, object pose estimation to parallel gripper grasping estimation
dataworks 同步maxcomputer 到sqlserver ,汉字变乱码了,请问怎么解决
如何利用AI技术优化独立站客服系统?听听专家怎么说!
【驚了】迅雷下載速度竟然比不上虛擬機中的下載速度
Redis-缓存问题