当前位置:网站首页>LeetCode Algorithm 2326. 螺旋矩阵 IV
LeetCode Algorithm 2326. 螺旋矩阵 IV
2022-07-30 04:42:00 【Alex_996】
题目链接:2326. 螺旋矩阵 IV
Ideas
算法:边界压缩
数据结构:链表
思路:印象中好像刚开始学算法的时候就遇到过类似的题目,什么旋转打印矩阵之类的,跟这道题类似。
- 首先创建一个 m * n 的矩阵,默认用 -1 填充即可;
- 定义up、down、left、right四个变量,分别表示矩阵的四个边界;
- 遍历链表往矩阵里面填数,完成一行或一列之后就压缩对应的边界,行和列遍历的顺序就是顺时针遍历。
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;
}
};
边栏推荐
- 动态规划问题(完结篇)
- 复现XXL-JOB 任务调度中心后台任意命令执行漏洞
- 文件系统二
- 我的Go+语言初体验——祝福留言小系统,让她也可以感受到你的祝福
- GCC Rust is approved to be included in the mainline code base, or will meet you in GCC 13
- [Linear table] - Detailed explanation of three practice questions of LeetCode
- A must see for software testers!Database knowledge MySQL query statement Daquan
- How to use labelme
- 【周周有奖】云原生编程挑战赛“边缘容器”赛道邀你来战!
- protobuf 中复合数据类型的读写
猜你喜欢

cnpm安装步骤

【软件工程之美 - 专栏笔记】31 | 软件测试要为产品质量负责吗?

swagger usage tutorial - quick use of swagger

我的Go+语言初体验——祝福留言小系统,让她也可以感受到你的祝福

【线性表】- LeetCode力扣三道练习题详解

六、读取应用配置+日志配置

Android Studio 实现登录注册-源代码 (连接MySql数据库)

@ WebServlet annotations (Servlet annotations)

2.6 Merge Sort

Machine Learning: Knowing the Dimensionality Reduction Process Through Low Variance Filtering
随机推荐
The 2nd Shanxi Province Network Security Skills Competition (Enterprise Group) Part of the WP (9)
[C language] Program environment and preprocessing
Simulation Problem (Part 1)
Introduction to Thymeleaf
Naive Bayes Classification
Image stitching (registration) case based on OpenCV
VUX Datetime 组件compute-days-function动态设置日期列表
nSoftware.PowerShell.Server.2020
《构建之法》笔记---第十章 典型用户和场景
深圳见!云原生加速应用构建专场:来看云原生 FinOps、SRE、高性能计算场景最佳实践
共建共享数字世界的根:阿里云打造全面的云原生开源生态
Notes on "The Law of Construction"---Chapter 10 Typical Users and Scenarios
Go study notes (84) - Go project directory structure
05 Detailed explanation of the global configuration file application.properties
【线性表】- LeetCode力扣三道练习题详解
【软件工程之美 - 专栏笔记】31 | 软件测试要为产品质量负责吗?
POJ1321 棋盘问题(详解)
BGP的简单实验
Stimulsoft ReportsJS and DashboardsJS. 2022.3.3
Alibaba Cloud's EasyNLP Chinese text image generation model takes you to become an artist in seconds