当前位置:网站首页>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-07-24 14:15: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
边栏推荐
- Detailed explanation of MSTP protocol for layer 3 switch configuration [Huawei ENSP experiment]
- R language uses the statstack function of epidisplay package to view the statistics (mean, median, etc.) of continuous variables and the corresponding hypothesis test in a hierarchical manner based on
- CSDN垃圾的没有底线!
- 清除字符串中所有空格
- 字符串——28. 实现 strStr()
- Multithreaded common classes
- sql server语法—创建数据库
- 不要灰心,大名鼎鼎的YOLO、PageRank影响力爆棚的研究,曾被CS顶会拒稿
- Stack and queue -- 232. Implement queue with stack
- Unity 委托 (Delegate) 的简单理解以及实现
猜你喜欢

Su Chunyuan, founder of science and technology · CEO of Guanyuan data: making business use is the key to the Bi industry to push down the wall of penetration

【NLP】下一站,Embodied AI

OWASP zap security testing tool tutorial (Advanced)

uni-app 背景音频 熄屏或者退回桌面之后不在播放

电赛设计报告模板及历年资源

Mmdrawercontroller first loading sidebar height problem

达梦实时主备集群搭建

Matlab program for natural gas flow calculation
![[oauth2] III. interpretation of oauth2 configuration](/img/31/90c79dbc91ee15c353ec46544c8efa.png)
[oauth2] III. interpretation of oauth2 configuration

Typo in static class property declarationeslint
随机推荐
uni-app 背景音频 熄屏或者退回桌面之后不在播放
如何在Ubuntu 18.04和Debian 9上安装PHP 5.6
Add an element to the object array with unshift
学习scipy minimize
bibliometrix: 从千万篇论文中挖掘出最值得读的那一篇!
Nodejs uses the express framework to post the request message "badrequesterror:request aborted"
Where can Huatai Securities open an account? Is it safe to use a mobile phone
Mmdrawercontroller first loading sidebar height problem
[oauth2] II. Known changes in oauth2.1
TypeError: Cannot read property ‘make‘ of undefined
String - Sword finger offer 58 - ii Rotate string left
sql server语法—创建数据库
CSDN垃圾的没有底线!
Learn science minimize
解决 uni-starter 使用本地函数可以登录微信 但是使用云函数登录失败
电赛设计报告模板及
Unity pedestrians walk randomly without collision
2022年IAA行业品类发展洞察系列报告·第二期
Beijing all in one card listed and sold 68.45% of its equity at 352.888529 million yuan, with a premium rate of 84%
Stack and queue -- 232. Implement queue with stack