目录
牛客_顺时针打印矩阵
对于一个矩阵,请设计一个算法从左上角(mat[0][0])开始,顺时针打印矩阵元素。
给定int矩阵mat,以及它的维数nxm,请返回一个数组,数组中的元素为矩阵元素的顺时针输出。
测试样例:
[[1,2],[3,4]],2,2
返回:[1,2,4,3]
解析代码
- 1. 先记录左上角和右下角坐标(这两个坐标就描述了一个矩形)。
- 2. 然后先按照顺时针打印这个矩形边上的元素。
- 3. 缩小矩形(也就是调整左上和右下坐标位置)。
- 4. 再次顺时针打印.一直缩小到这个矩形为空即可。
class Printer {
public:
vector<int> clockwisePrint(vector<vector<int> > mat, int n, int m) {
// write code here
// 左上角坐标
int x1 = 0;
int y1 = 0;
// 右下角坐标
int x2 = n - 1;
int y2 = m - 1;
vector<int> ret;
while (x1 <= x2 && y1 <= y2)
{
// 第一行: x1, y1 ~ y2
for (int i = y1; i <= y2; ++i)
{
ret.push_back(mat[x1][i]);
}
// 最后一列:x1 + 1 ~ x2, y2
for (int i = x1 + 1; i <= x2; ++i)
{
ret.push_back(mat[i][y2]);
}
// 最后一行: x2, y2 - 1 ~ y1 --> x1 < x2
if (x1 < x2)
{
for (int i = y2 - 1; i >= y1; --i)
{
ret.push_back(mat[x2][i]);
}
}
// 第一列:x2 - 1 ~ x1 + 1, y1 --> y1 < y2
if (y1 < y2)
{
for (int i = x2 - 1; i > x1; --i)
{
ret.push_back(mat[i][y1]);
}
}
x1++;
y1++;
x2--;
y2--;
}
return ret;
}
};