题目描述
蛇形矩阵
多考虑思路,灵活运用,多看
样例
#include <iostream>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
int matrix[100][100];
int num = 1;
int top = 0, bottom = n - 1, left = 0, right = m - 1;
while (num <= n * m) {
// 从左到右填充顶部行
for (int j = left; j <= right && num <= n * m; j++) {
matrix[top][j] = num++;
}
top++;
// 从上到下填充右列
for (int i = top; i <= bottom && num <= n * m; i++) {
matrix[i][right] = num++;
}
right--;
// 从右到左填充底部行
for (int j = right; j >= left && num <= n * m; j--) {
matrix[bottom][j] = num++;
}
bottom--;
// 从下到上填充左列
for (int i = bottom; i >= top && num <= n * m; i--) {
matrix[i][left] = num++;
}
left++;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}