当前位置:网站首页>LeetCode 面试题29 顺时针打印矩阵
LeetCode 面试题29 顺时针打印矩阵
2022-06-26 18:07:00 【Maccy37】
代码搬运工就是我啦!
参考LeetCode官网链接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/solution/shun-shi-zhen-da-yin-ju-zhen-by-leetcode-solution/
题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印每一个数字。
示例1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5]
示例2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] 输出:[1,2,3,4,8,12,11,10,9,5,6,7]
限制:
0 <= matrix.length <= 1000 <= matrix[i].length <= 100
看了《剑指offer》里面的解题还是不理解他的代码
解题方法:按层模拟
可以将矩阵看成若干层,首先打印最外层的元素,其次打印次外层的元素,直到打印最内层的元素。
定义矩阵的第 k层是到最近边界距离为 kk的所有顶点。例如,下矩阵最外层元素都是第 1 层,次外层元素都是第 2 层,剩下的元素都是第 3层。
[1, 1, 1, 1, 1, 1, 1],
[1, 2, 2, 2, 2, 2, 1],
[1, 2, 3, 3, 3, 2, 1],
[1, 2, 2, 2, 2, 2, 1],
[1, 1, 1, 1, 1, 1, 1]
对于每层,从左上方开始以顺时针的顺序遍历所有元素。假设当前层的左上角位于(top,left),右下角位于(bottom,right),按照如下顺序遍历当前层的元素。
1.从左到右遍历上侧元素,依次为 (top,left) 到 (top,right)。
2.从上到下遍历右侧元素,依次为 (top+1,right)到(bottom,right)
3.如果 left<right 且 top<bottom,则从右到左遍历下侧元素,依次为(bottom,right-1)到(bottom,left+1),以及从下到上遍历左侧元素,依次为(bottom,left)到(top+1,left)

class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(matrix.size()<=0||matrix[0].size()<=0)
return {};
int rows=matrix.size(),columns=matrix[0].size();
int left=0,right=columns-1,top=0,bottom=rows-1;
vector<int>order;
while(left<=right&&top<=bottom)
{
for(int column=left;column<=right;column++)
{
order.push_back(matrix[top][column]);
}
for(int row=top+1;row<=bottom;row++)
{
order.push_back(matrix[row][right]);
}
if(left<right&&top<bottom)
{
for(int column=right-1;column>left;column--)
{
order.push_back(matrix[bottom][column]);
}
for(int row=bottom;row>top;row--)
{
order.push_back(matrix[row][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return order;
}
};发现这种解题思路更容易理解。
边栏推荐
- MySQL的MVCC机制详解
- Detailed explanation of asymmetric cryptosystem
- Detailed explanation of MySQL mvcc mechanism
- 临时关闭MySQL缓存
- How sparksql returns a specific day of the week by date -dayofweek function
- Temporarily turn off MySQL cache
- Plt How to keep show() not closed
- Bayesian network explanation
- 股票开账户如何优惠开户?现在在线开户安全么?
- 在国金证券开户怎么样?开户安全吗?
猜你喜欢
随机推荐
JNI的 静态注册与动态注册
Bayesian network explanation
wm_concat()和group_concat()函数
腾讯钱智明:信息流业务中的预训练方法探索与应用实践
Li Kou daily question - day 28 -566 Reshape matrix
ZCMU--1367: Data Structure
A little experience of next (ITER (dataloader))
Applet setting button sharing function
Halcon's region: features of multiple regions (5)
Digital signature standard (DSS)
比较两个对象的大小关系原来可以如此花里胡哨
Hello, is it safe to open an online stock account and buy stocks now?
数据加密标准(DES)概念及工作原理
Row lock analysis and deadlock
padding百分比操作
数字签名标准(DSS)
输入n个整数,输出出现次数大于等于数组长度一半的数
#26class中get和set设置
数据加密标准DES安全性
股票开账户如何优惠开户?现在在线开户安全么?

![[buuctf.reverse] 126-130](/img/df/e35633d85caeff1dece62a66cb7804.png)






