当前位置:网站首页>剑指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;
}边栏推荐
- 一步步把 SAP UI5 应用部署到 SAP BTP Kyma 运行环境中去
- Leetcode-110-balanced binary tree
- JVM|本地方法接口;本地方法栈
- 一个Golang的私有库设置问题
- JVM | virtual machine stack (local variable table; operand stack; dynamic link; method binding mechanism; method call; method return address)
- BZOJ3189 : [Coci2011] Slika
- JVM|运行时数据区;程序计数器(PC寄存器);
- Codeforces Round #744 (Div. 3) 解题报告
- Customer information management software
- How to import workflows provided on SAP API hub to sap BTP
猜你喜欢

数据库每日一题---第9天:销售员

Answer fans' questions | count the number and frequency of letters in the text

LabVIEW Arduino electronic weighing system (project Part-1)

LeetCode-110-平衡二叉树
![[v2.1] automatic update system based on motion step API (repair bug, increase completion display, support disconnection reconnection and data compensation)](/img/73/2ec957d58616d692e571a70826787f.jpg)
[v2.1] automatic update system based on motion step API (repair bug, increase completion display, support disconnection reconnection and data compensation)

ESP32C3 Arduino库使用方法

servlet获取表单数据
![BZOJ3189 : [Coci2011] Slika](/img/46/c3aa54b7b3e7dfba75a7413dfd5b68.png)
BZOJ3189 : [Coci2011] Slika

RPA丨首席财务官如何找到数字化转型“超级入口”?

Endnotex9 introduction and basic tutorial instructions
随机推荐
Refresh and upgrade | innovation, starting from cloud store
Using the sap ui5 cli command line tool to build and run SAP ui5 applications
Test plans and test cases
LabVIEW控制Arduino实现红外测距(进阶篇—6)
CANN编码的一些报错汇编
EndnoteX9简介及基本教程使用说明
Redis basic data type (Zset) ordered collection
联调这夜,我把同事打了...
How to create the simplest SAP kyma function
Usage of esp32c3 Arduino Library
Redis data type (string)
AC自动机
Educational codeforces round 111 (rated for Div. 2) C Supplement
Codeforces Round #742 (Div. 2) F. One-Four Overload
领先企业推进智慧财务的同款效率工具,赶快了解一下?
ESP32C3 Arduino库使用方法
Codeworks round 744 (Div. 3) problem solving Report
JVM | local method interface; Native Method Stack
Endnotex9 introduction and basic tutorial instructions
RPA+低代码助推品牌电商启新创变、重启增长