当前位置:网站首页>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;
}
}
边栏推荐
- What else do entrepreneurs need besides money? Exclusive interview with Mingyue Lake venture capital institutions
- Record the process of the first excavation and intersection
- STM32单片机使用ADC功能驱动手指检测心跳模块
- Matlab小波工具箱导入信号出错(doesn‘t contain one dimensional Singal)
- Golang invalid argument to intn报错的解决
- El select drop-down box multi selection remote search anti display
- 接口测试
- Storage structure and management disk. It's a bit like installing Win98. You need to partition and format the hard disk first
- LeetCode高频题62. 不同路径:机器人从左上角到右下角的路径有多少条?纯概率排列组合问题,而不是动态规划题
- Leetcode high frequency question 62. different paths: how many paths does the robot have from the upper left corner to the lower right corner? Pure probability permutation and combination problem, not
猜你喜欢

淘宝助理停用,用大淘营导入数据包上传宝贝提示“主图为必填项,不能为空”是什么原因?如何解决?

PCL error: error c2589 "(": "::" illegal mark on the right)

记第一次挖洞交洞历程

海外资深玩家的投资建议(3) 2021-05-04

大学数据库创建与查询实战——数据库表设计

Leetcode high frequency question 62. different paths: how many paths does the robot have from the upper left corner to the lower right corner? Pure probability permutation and combination problem, not

Stm32+esp8266+mqtt protocol connects Alibaba cloud Internet of things platform

138 - query case - knowledge points involved: foreach traversal & computed calculation attributes & V-for loop

LeetCode高频题62. 不同路径:机器人从左上角到右下角的路径有多少条?纯概率排列组合问题,而不是动态规划题

除了钱,创业者还需要什么?专访明月湖创赛创投机构
随机推荐
【HiFlow】腾讯云新一代自动化助手,我用它完成了企业疫情提示(无代码)
接口测试
产品生命周期,常见的项目职能,信息流 都是什么
How can I open an account to buy financial products with a 6% income?
Taobao assistant is disabled. What is the reason for using the big Taoying import data package to upload the baby prompt "the main image is required and cannot be empty"? How to solve it?
U++ 学习笔记 控制物体Scale
年化收益率6%的理财产品
JS——事件代理和应用场景
JDBC programming of MySQL
Can Verilog of synthetizable be integrated
Jmeter性能综合实战——签到及批量签到
STM32+ESP8266+MQTT协议连接阿里云物联网平台
University database creation and query practice -- database table design
小说里的编程 【连载之十九】元宇宙里月亮弯弯
Bisection function details
Still worrying about xshell cracking, try tabby
【AcWing】周赛
MVVM和MVVMLight简介及项目开发(一)
Neo4j应用
Basic character axis binding and mapping binding of u++ learning notes