当前位置:网站首页>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
边栏推荐
猜你喜欢

Solve the problem that the ARR containsobject method returns no every time

使用树莓派做Apache2 HA实验

对话框管理器第二章:创建框架窗口

Dialog manager Chapter 2: create frame window
![The solution to the error of [installation detects that the primary IP address of the system is the address assigned by DHCP] when installing Oracle10g under win7](/img/25/aa9bcb6483bb9aa12ac3730cd87368.png)
The solution to the error of [installation detects that the primary IP address of the system is the address assigned by DHCP] when installing Oracle10g under win7

Csp2021 T3 palindrome

Unity行人随机行走不碰撞

Concurrent programming ----------- set
![Rasa 3.x 学习系列-Rasa [3.2.4] - 2022-07-21 新版本发布](/img/1e/27f107d514ded6641410cc5a45764b.png)
Rasa 3.x 学习系列-Rasa [3.2.4] - 2022-07-21 新版本发布

Rhcsa sixth note
随机推荐
Solve the problem that the ARR containsobject method returns no every time
达梦实时主备集群搭建
Default color setting in uiswitch off state
"XXX" cannot be opened because the identity of the developer cannot be confirmed. Or what file has been damaged solution
Rasa 3.x 学习系列-Rasa [3.2.4] - 2022-07-21 新版本发布
本机异步网络通信执行快于同步指令
Summary of week 22-07-23
[oauth2] IV. oauth2authorizationrequestredirectfilter
Ansible installation and deployment of automated operation and maintenance
字符串——剑指 Offer 58 - II. 左旋转字符串
【NLP】下一站,Embodied AI
Regular expression and bypass cases
Typo in static class property declarationeslint
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
Automated penetration scanning tool
Build ZABBIX monitoring service in LNMP architecture
Ztree tree Metro style mouse through the display user-defined controls add, edit, delete, down, up operations
C language -- three ways to realize student information management
Atcoder beginer contest 261e / / bitwise thinking + DP
Beijing all in one card listed and sold 68.45% of its equity at 352.888529 million yuan, with a premium rate of 84%