AcWing 756. 蛇形矩阵


#include 

using namespace std;
const int N = 110;
int res[N][N], n, m, x, y, d = 0;
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
int main()
{
    cin >> n >> m;
    for(int i = 1; i <= n*m; i++){
        res[x][y] = i;
        int a = x + dx[d], b = y + dy[d];
        if(a >= n || b >= m || a < 0 || b < 0 || 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;
}

 题目地址:https://www.acwing.com/activity/content/problem/content/1898/