AcWing 756. 蛇形矩阵
原题链接
简单
作者:
拭
,
2021-04-28 14:30:29
,
所有人可见
,
阅读 257
#include <iostream>
#include <vector>
using namespace std;
int main() {
int m, n; cin >> m >> n;
vector<vector<int>> nums(m, vector<int>(n, 0));
int dx[] = {0,1,0,-1};
int dy[] = {1,0,-1,0};
for (int k = 1, x = 0, y = 0, d = 0; k <= n*m; k++) {
nums[x][y] = k;
int nx = x + dx[d]; int ny = y + dy[d];
if (nx >= m || ny >= n || nx < 0 || ny < 0 || nums[nx][ny]) {
d = (d + 1) % 4;
nx = x + dx[d];
ny = y + dy[d];
}
x = nx;
y = ny;
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cout << nums[i][j] << " ";
}
cout << endl;
}
return 0;
}