欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

(入门组)寒假每日一题 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;   
}