题目
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
样例
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
解法:模拟
通过while循环去模拟每一圈的打印过程即可
主要是需要通过画图想清楚边界条件
时间复杂度O(n^2),空间复杂度O(1)
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> ans;
if (matrix.empty()) return ans;
int hmax = matrix.size() - 1, wmax = matrix[0].size() - 1;
int hmin = 0, wmin = 0;
while (hmin <= hmax && wmin <= wmax) {
// cout << hmin << ' ' << hmax << ' ' << wmin << ' ' << wmax << endl;
print(hmin, hmax, wmin, wmax, matrix, ans);
hmin++, hmax--;
wmin++, wmax--;
}
return ans;
}
void print(int hmin, int hmax, int wmin, int wmax, const vector<vector<int>> matrix, vector<int> &ans) {
for (int i = wmin; i <= wmax; i++) {
ans.push_back(matrix[hmin][i]);
}
for (int i = hmin + 1; i <= hmax; i++) {
ans.push_back(matrix[i][wmax]);
}
if (hmin < hmax) { // 多于1行
for (int i = wmax - 1; i >= wmin; i--) {
ans.push_back(matrix[hmax][i]);
}
}
if (wmin < wmax) { // 多于1列
for (int i = hmax - 1; i > hmin; i--) {
ans.push_back(matrix[i][wmin]);
}
}
}
};