欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > 面试题 29. 顺时针打印矩阵

面试题 29. 顺时针打印矩阵

2024/10/24 19:23:26 来源:https://blog.csdn.net/weixin_51332735/article/details/140475999  浏览:    关键词:面试题 29. 顺时针打印矩阵

顺时针打印矩阵

  • 题目描述
    • 示例
  • 题解

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

示例

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

题解

从外往里一圈一圈遍历并存储矩阵元素即可。

class Solution {
public:vector<int> spiralOrder(vector<vector<int>>& matrix) {int rows = matrix.size(), cols = matrix[0].size();if (rows == 0 || cols == 0) return {};vector<int> res;int top = 0, bottom = rows -1, left = 0, right = cols - 1;while (top <= bottom && left <= right) {for (int i = left; i <= right; i++) res.push_back(matrix[top][i]);for (int i = top + 1; i <= bottom; i++) res.push_back(matrix[i][right]);// 判断不可少if (left < right && top < bottom) {for (int i = right - 1; i >= left; i--) res.push_back(matrix[bottom][i]);// 可以模拟发现 不可以为 i >= topfor (int i = bottom - 1; i > top; i--) res.push_back(matrix[i][left]);}top++;bottom--;left++;right--;}return res;}
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com