当前位置:网站首页>Array - 59. Spiral matrix II
Array - 59. Spiral matrix II
2022-07-23 22:15:00 【Xiao Zhao, who is working hard for millions of annual salary】
1 Title Description
- Spiral matrix II
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 .
2 Title Example

Input :n = 3
Output :[[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input :n = 1
Output :[[1]]
3 Topic tips
- 1 <= n <= 20
4 Ideas
This question does not involve any algorithm , Is the simulation process , But they are very concerned about the ability to control the code .
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
From outside to inside, circle by circle .
Each side should be consistently closed to the left and opened to the right , Or the principle of opening left and closing right , In this way, the circle can be drawn according to the unified rules .
5 My answer
class Solution {
public int[][] generateMatrix(int n) {
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;
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++) {
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--) {
res[i][j] = count++;
}
// Simulate the left side from bottom to top
for (; i >= loop; i--) {
res[i][j] = count++;
}
start++;
}
if (n % 2 == 1) {
res[start][start] = count;
}
return res;
}
}
C++ Code :
This paragraph is quoted from the code Capriccio
Spiral matrix II
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0)); // Use vector Define a two-dimensional array
int startx = 0, starty = 0; // Define the starting position of each cycle
int loop = n / 2; // How many times per cycle , for example n It's odd 3, that loop = 1 Just a cycle , The values in the middle of the matrix need to be treated separately
int mid = n / 2; // In the middle of the matrix , for example :n by 3, The middle position is (1,1),n by 5, The middle position is (2, 2)
int count = 1; // Used to assign a value to each space in the matrix
int offset = 1; // You need to control the length of each edge traversal , The right boundary of each cycle shrinks by one digit
int i,j;
while (loop --) {
i = startx;
j = starty;
// The following four for It's a simulation turn
// Analog fill uplink from left to right ( Left closed right away )
for (j = starty; j < n - offset; j++) {
res[startx][j] = count++;
}
// The simulation fills the right column from top to bottom ( Left closed right away )
for (i = startx; i < n - offset; i++) {
res[i][j] = count++;
}
// The simulation fills down from right to left ( Left closed right away )
for (; j > starty; j--) {
res[i][j] = count++;
}
// Simulate filling the left column from bottom to top ( Left closed right away )
for (; i > startx; i--) {
res[i][j] = count++;
}
// At the beginning of the second lap , The starting position shall be added with 1, for example : The starting position of the first circle is (0, 0), The starting position of the second circle is (1, 1)
startx++;
starty++;
// offset Control the length of each edge traversal in each circle
offset += 1;
}
// If n For an odd number , You need to assign a separate value to the middle of the matrix
if (n % 2) {
res[mid][mid] = count;
}
return res;
}
};
Similar topics :
- 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 .
Tips :
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
For this spiral traversal method , The important thing is to determine the position of the upper, lower, left and right sides , So when initializing , above up Namely 0, Underside down Namely m-1, On the left left yes 0, On the right right yes n-1. And then we do while loop , Traverse the upper edge first , Add all elements to the result res, Then move one position up and down , If the upper side is larger than the lower side , It indicates that the traversal has been completed at this time , direct break.
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return new LinkedList<>();
int l = 0;
int r = matrix[0].length - 1;
int u = 0;
int d = matrix.length - 1;
List<Integer> list = new LinkedList<>();
while (l <= r && u <= d){
for (int i = l; i <= r; i++) {
list.add(matrix[u][i]);
}
u++;
for (int i = u; i <= d; i++) {
list.add(matrix[i][r]);
}
r--;
for (int i = r; i >= l && u <= d; i--) {
list.add(matrix[d][i]);
}
d--;
for (int i = d; i >= u && l <= r; i--) {
list.add(matrix[i][l]);
}
l++;
}
return list;
}
}
边栏推荐
猜你喜欢

记忆化搜索 - DP

【golang学习笔记】Go语言中参数的传递是值传递还是引用传递

JMeter performance comprehensive practice - sign in and batch sign in

机器学习习题——对率回归

Memory search - DP

Description and implementation of throttling and anti shake

Lambda learning (the use of comparator after sort and collectors.groupingby after collection)

How does MySQL prepare SQL (solve the problem that in query SQL preprocessing can only query one record)

Cookies and sessions

【数学建模暑期培训】配送中心选址问题
随机推荐
王学岗视频编码————MediaCodec编解码
实时监控Mysql数据库变化_进行数据同步_了解Canal_---Canal工作笔记001
LeetCode高频题62. 不同路径:机器人从左上角到右下角的路径有多少条?纯概率排列组合问题,而不是动态规划题
Storage structure and management disk. It's a bit like installing Win98. You need to partition and format the hard disk first
Neo4j应用
10道面试基础笔试题,你能对几题?
Jedis 6 - Introduction and difference between redisson and jedis
[golang learning notes] concurrency basis
Investment suggestions for overseas senior players (2) 2021-05-03
Basic character axis binding and mapping binding of u++ learning notes
U++学习笔记 基础人物轴绑定及映射绑定
Altium designer—Arduino UNO原理图&PCB图(自制Arduino板)
Inspiration from Buffett's shareholders' meeting 2021-05-06
年化收益率6%的理财产品
Is Ping An Securities' low commission account opening link safe? How to handle low commission
小说里的编程 【连载之十九】元宇宙里月亮弯弯
Description and implementation of throttling and anti shake
达梦数据库tools包中的工具(操作达梦数据库)
Comparison of open source distributed link tracking
【学习笔记】树的直径,重心