【よくわかる】ABC335 D問題 Loong and Takashi

At Coder

ABC335のD問題 Loong and Takashi の解説です。

コード

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for (int i = 0; i < (n); ++i)
int main() {
    int n;
    cin >> n;
    vector<vector<int>>grid(n, vector(n, 0));

    vector dy = {0, -1, 0, 1};
    vector dx = {1, 0, -1, 0};
    int dir = 0;

    int y = 0;
    int x = 0;
    grid[0][0] = 1;
    int cnt = 2;

    while (cnt <= n * n) {
       int next_y = y + dy[dir];
       int next_x = x + dx[dir];
       if (next_y >= 0 && next_y < n && next_x >= 0 && next_x < n && grid[next_y][next_x] == 0) {
            grid[next_y][next_x] = cnt;
            cnt++;
            y = next_y;
            x = next_x;
        } else {
            dir++;
            dir %= 4;
        }
    }

    rep(i, n) {
        rep(j, n) {
            if (grid[i][j] == n * n) cout << "T ";
            else cout << grid[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

解説動画リンク

解説動画はこちらです。

コメント