#include <iostream>
#include <vector>
using namespace std;
void printMatrix(vector<vector<int> > m) {
if (m.empty()) return;
int rows = m.size();
int cols = m[0].size();
// 四个角落
int left = 0;
int right = cols - 1;
int top = 0;
int dow = rows - 1;
while (left <= right && top <= dow) {
// 从左到右
if (left <= right) {
for (int i = left; i <= right; i++) cout << m[top][i] << " ";
}
// 从上到下
if (++top <= dow) {
for(int i=top;i<=dow;i++) cout << m[i][right] << " ";
}
// 从右往左
if (top <= dow && left <= --right) {
for (int i = right; i >= left; i--) cout << m[dow][i] << " ";
}
// 从下往上
if (top <= --dow && left <= right) {
for (int i = dow; i >= top; i--) cout << m[i][left] << " ";
}
left++;
}
return;
}
int main() {
vector<vector<int>> m = { {1,2,3,4},{5,6,7,8},{9,10,11,12} };
printMatrix(m);
}
顺时针打印矩阵
最新推荐文章于 2024-09-02 20:21:30 发布