当前位置:网站首页>剑指Offer 29.顺时针打印矩阵
剑指Offer 29.顺时针打印矩阵
2022-06-11 21:36:00 【爱学代码的学生】
题目描述:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
题目分析:
以顺时针的顺序打印,那我们可以将其分成四个步骤:
1. 从左往右
2. 从上往下
3. 从右往左
4. 从下往上
因此我们可以将矩阵的四个边所在的行或列分别表示出来。
每一次打印完以后我们将其所在的行或者列进行+-1,用来缩小矩阵,来说明我们已经走过此段。
代码如下:
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize){
if(matrixSize==0){
*returnSize=0;
return NULL;
}
*returnSize=matrixSize*(*matrixColSize);//求出矩阵中元素个数
int up=0,down=matrixSize-1;//四个边界
int left=0,right=*matrixColSize-1;
int*ret=(int*)malloc(sizeof(int)*(*returnSize));//构造数组
int index=0;
while(index<*returnSize){
for(int i=left;index<*returnSize&&i<=right;i++){//从左->右
ret[index++]=matrix[up][i];
}
up++; //缩小矩阵
for(int i=up;index<*returnSize&&i<=down;i++){//从上->下
ret[index++]=matrix[i][right];
}
right--;
for(int i=right;index<*returnSize&&i>=left;i--){//从右->左
ret[index++]=matrix[down][i];
}
down--;
for(int i=down;index<*returnSize&&i>=up;i--){//从下->上
ret[index++]=matrix[i][left];
}
left++;
}
return ret;
}边栏推荐
- JVM|前言介绍
- Codeforces Round #740 Div. 2 解题报告
- Building a custom CNN model: identifying covid-19
- CANN编码的一些报错汇编
- Endnotex9 introduction and basic tutorial instructions
- Common file functions
- Usage of esp32c3 Arduino Library
- Leetcode-43- string multiplication
- Redis basic data type (Zset) ordered collection
- Codeforces Round #742 (Div. 2) F. One-Four Overload
猜你喜欢

Leetcode-104- maximum depth of binary tree

EndnoteX9簡介及基本教程使用說明

Leetcode-32- longest valid bracket

flutter系列之:flutter中常用的container layout详解

2021 Niuke multi school 5 double strings
![BZOJ3189 : [Coci2011] Slika](/img/46/c3aa54b7b3e7dfba75a7413dfd5b68.png)
BZOJ3189 : [Coci2011] Slika

Test plans and test cases

The network connection is normal, but Baidu web page can not be opened and displayed. You can't access this website solution

Leetcode-155-minimum stack

A collection of commonly used open source data sets for face recognition
随机推荐
Iros 2021 | new idea of laser vision fusion? Lidar intensity diagram +vpr
Refresh and upgrade | innovation, starting from cloud store
行而不辍,未来可期|云扩科技入选上海市专精特新企业
作为一名 ABAP 资深顾问,下一步可以选择哪一门 SAP 技术作为主攻方向?
Leetcode-104- maximum depth of binary tree
Redis data type (string)
Redis Foundation
Common file functions
Leetcode-322- change exchange
Flutter series: detailed explanation of container layout commonly used in flutter
Database daily question --- day 9: salesperson
【C語言進階】整型在內存中的存儲
多态的所有特征
二分图King
Leetcode-98- validate binary search tree
JVM class loader; Parental delegation mechanism
LabVIEW控制Arduino实现红外测距(进阶篇—6)
Game client performance (memory) [previous]
Codeforces Round #742 (Div. 2) F. One-Four Overload
Codeforces Round #742 (Div. 2) F. One-Four Overload