Submission

Status:

[PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP]

Score: 100

User: njoop

Problemset: ย่องเบาหลบกับระเบิด

Language: cpp

Time: 0.088 second

Submitted On: 2025-05-20 18:48:02

#include <bits/stdc++.h>

using namespace std;

#define int long long
#define double long double
#define pii pair <int, int>
#define tiii tuple <int, int, int>
#define tiiii tuple <int, int, int, int>
#define emb emplace_back
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define iShowSpeed cin.tie(NULL)->sync_with_stdio(false)

const int inf = 1e18;

int dx[] = {1, 0, -1, 0, 1, 1, -1, -1};
int dy[] = {0, 1, 0, -1, 1, -1, 1, -1};

int n, m, a[1010][1010], b[1010][1010]; 

bool inside(int x, int y){
    return !(x < 1 || x > n || y < 1 || y > m);
}

int32_t main(){
    iShowSpeed;
    cin >> n >> m;
    for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cin >> b[i][j], b[i][j] = 1 - b[i][j];
    for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (b[i][j]) {
        int x = i, y = j; a[x][y] = 1;
        for (int k = 0; k < 8; k++) {
            int nx = x + dx[k], ny = y + dy[k];
            if (!inside(nx, ny)) continue;
            a[nx][ny] = 1;
        }
    }
    // for (int i = 1; i <= n; i++) {
    //     for (int j = 1; j <= m; j++) {
    //         cout << a[i][j] << " ";
    //     }
    //     cout << "\n";
    // }
    queue <tiii> q; for (int i = 1; i <= n; i++) if (!a[i][1]) q.emplace(1, i, 1);
    int dis[n + 1][m + 1]; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) dis[i][j] = inf;
    int ans = inf;
    while (!q.empty()) {
        auto [w, x, y] = q.front(); q.pop();
        // cout << "(" << x << ", " << y << "): " << w << "\n";
        if (y == m) {
            ans = w;
            break;
        }
        if (w > dis[x][y]) continue;
        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i], ny = y + dy[i];
            // cout << x << ", " << y << " -> " << nx << ", " << ny << "\n";
            if (!inside(nx, ny) || a[nx][ny]) continue;
            int nw = w + 1;
            if (nw < dis[nx][ny]) {
                dis[nx][ny] = nw;
                q.emplace(dis[nx][ny], nx, ny);
            }
        }
        // cout << "--------------------------\n";
    }
    cout << (ans == inf ? -1 : ans);
}