本文主要是介绍牛客_顺时针打印矩阵_C++题解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目来源:牛客
题目缩写:给你一个矩阵(vector<vector<int>>)让你将它的值按顺时针的方式存在一个一维vector<int>中,然后返回;
简要分析:
① 迭代,先打印第一行,然后最右列,然后最后一行,然后最左列.....
② 存第一行的值到vector<int>中,然后删除第一行,然后逆时针90°旋转矩阵,再存第一行的值到vector<int>中,然后删除第一行......
以第一种方法为例,C++代码实现如下:
class Printer
{
public:vector<int> clockwisePrint(vector<vector<int> > mat, int n, int m) {vector<int> res;int left = 0,right = m-1,top = 0,bottom = n-1;while(left<=right&&top<=bottom){for(int i = left;i<=right;i++) res.push_back(mat[top][i]);for(int i=top+1;i<=bottom;i++) res.push_back(mat[i][right]);for(int i=right-1;i>=left&&top<bottom;i--) res.push_back(mat[bottom][i]);for(int i=bottom-1;i>=top+1&&left<right;i--) res.push_back(mat[i][left]);top++;bottom--;left++;right--;}return res;}
};
【注】:第三个for循环中写了 top<bottom ,可以这样理解,如果这个矩阵只有1行,那么top==bottom,如果此时没有 top<bottom 的话,就会把第一行再打印1遍;
同理,第四个for循环中写了 left<right 可以想象如果这个矩阵是多行一列的情况,第二个for循环已经打印了这个列,如果没有这个判断条件,又会打印第二遍;
参考链接:链接
这篇关于牛客_顺时针打印矩阵_C++题解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!