当前位置:网站首页>LeetCode Algorithm 2326. Spiral Matrix IV
LeetCode Algorithm 2326. Spiral Matrix IV
2022-07-30 04:45:00 【Alex_996】
题目链接:2326. 螺旋矩阵 IV
Ideas
算法:边界压缩
数据结构:链表
思路:It seems that I have encountered similar problems when I first started learning algorithms,What rotates to print a matrix or something like that,similar to this.
- 首先创建一个 m * n 的矩阵,默认用 -1 填充即可;
- 定义up、down、left、right四个变量,represent the four boundaries of the matrix, respectively;
- Traverse the linked list to fill in the matrix,After completing a row or column, the corresponding boundary is compressed,The order in which rows and columns are traversed is clockwise.
Code
C++
class Solution {
public:
vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) {
vector<vector<int>> res(m, vector<int>(n, -1));
int up = 0, down = m - 1, left = 0, right = n - 1;
while (head) {
// 1.从左向右,行不变列变
for (int i = left; i < right + 1; i++) {
res[up][i] = head->val;
head = head->next;
if (head == nullptr) return res;
}
if (up < down) up++;
// 2.从上到下,列不变行变
for (int i = up; i < down + 1; i++) {
res[i][right] = head->val;
head = head->next;
if (head == nullptr) return res;
}
if (left < right) right--;
// 3.从右向左,行不变列变
for (int i = right; i > left - 1; i--) {
res[down][i] = head->val;
head = head->next;
if (head == nullptr) return res;
}
if (up < down) down--;
// 4.从下到上,列不变行变
for (int i = down; i > up - 1; i--) {
res[i][left] = head->val;
head = head->next;
if (head == nullptr) return res;
}
if (left < right) left++;
}
return res;
}
};
边栏推荐
猜你喜欢

(RCE) Remote Code/Command Execution Vulnerability Vulnerability Exercise

VUX Datetime 组件compute-days-function动态设置日期列表

See you in shenzhen!Cloud native to accelerate the application building special: see cloud native FinOps, SRE, high-performance computing scenario best practices

cnpm installation steps

动态规划问题(完结篇)

MySQL installation error solution

如何与墨西哥大众VW Mexico建立EDI连接

Using the GPU parallel computing 】 【 OpenCL&OpenCLUtilty GPU parallel computing

Learning of redis_Basic part

Unity3D Application simulation enters the front and background and pauses
随机推荐
C. Travelling Salesman and Special Numbers (binary + combination number)
22. 为什么需要消息队列?使用消息队列有什么好处?
The Double Pointer Problem (Part 1)
斐波那契数列的递归优化《备忘录递归》
GCC Rust is approved to be included in the mainline code base, or will meet you in GCC 13
WPF introduces ttf icon file usage record
labelme的使用技巧
字符串问题(下)
Naive Bayes Classification
Small programs use npm packages to customize global styles
[MRCTF2020]Hello_misc
模拟问题(中)
2.5 Quick Sort
Excellent MySQL interview questions, 99% must ask in preparation for August!I can't pass the interview
DAY17、CSRF 漏洞
VisualStudio2022本地调试进入特别慢问题解决
Requirements design document and the changing role of the product manager
The 2nd Shanxi Province Network Security Skills Competition (Enterprise Group) Partial WP (10)
A must see for software testers!Database knowledge MySQL query statement Daquan
Image stitching (registration) case based on OpenCV