zerofly's Blog

努力不一定成功,但不努力一定不会成功

0%

顺时针输出矩阵的值(C++)


刷题平台

牛客网

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如输入一个4×4矩阵:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16则依次打印出的数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

解题思路

依次遍历输出的过程:

  • 从左上角开始从左到右依次遍历输出;
  • 从上到下依次遍历输出;
  • 从右到左依次遍历输出;
  • 从下到上依次遍历输出;

其中黄色为遍历的起点,红色为遍历的终点。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution
{
public:
vector<int> printMatrix(vector<vector<int>> matrix)
{
int row = matrix.size();
int col = matrix[0].size();
vector<int> result; // 用于存放输出的结果
if (row == 0 && col == 0) // 判断矩阵是否为空
return result;

int left = 0, right = col -1, top = 0, bottom = row - 1;
while (left <= right && top <= bottom) // 判断矩阵是否遍历完
{
for (int i = left; i <= right; i++) //从左向右,注意i 的范围
result.push_back(matrix[top][i]);
for (int i = top + 1; i <= bottom; i++) // 从上到下,注意i的范围
result.push_back(matrix[i][right]);
if (top != bottom) //若top == bottom 则没有必要再从右向左遍历,因为已经遍历过了
{
for (int i = right - 1; i >= left; i--) // 从右向左,注意i的范围。
result.push_back(matrix[bottom][i]);
}
if (left != right) // 若left==right则没必要从下到上遍历,因为已经遍历过了
{
for (int i = bottom - 1; i > top; i--)// 从下向上,注意i的范围
result.push_back(matrix[i][left]);
}
left++,right--,top++,bottom--;
}
return result;
}
};

文章作者:zerofly

发布时间:2020年05月22日 - 09:05

原始链接:http://zeroflycui.github.io/d660613.html

许可协议: 转载请保留原文链接及作者。