(入门组)寒假每日一题 Week2
程序员文章站
2022-07-13 08:06:30
...
AcWing 756. 蛇形矩阵 (星期一)
分析
定义方向上右下左, 然后res里放元素即可
联动leetcode54
code
#include <iostream>
#include <vector>
using namespace std;
const int N = 110;
int n, m;
int main(){
scanf("%d%d", &n, &m);
int d = 1;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int x = 0, y = 0;
vector<vector<int>> res(n, vector<int>(m));
for (int i = 1; i <= n * m; i ++ ){
res[x][y] = i;
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a >= n || b < 0 || b >= m || res[a][b]){
d = (d + 1) % 4;
a = x + dx[d], b = y + dy[d];
}
x = a, y = b;
}
for (int i = 0; i < n; i ++ ){
for (int j = 0; j < m; j ++ )
cout << res[i][j] << ' ';
cout << endl;
}
return 0;
}
上一篇: openrest 操作 redis 相关
下一篇: Java 中关于不同进制转换的内置函数