Submission

Status:

[PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP]

Subtask/Task Score:

{100/100}

Score: 100

User: C12

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

Language: cpp

Time: 0.048 second

Submitted On: 2026-03-07 23:34:18

#include <bits/stdc++.h>

using namespace std;

#define ll long long

int posx[4] = {-1,1,0,0};
int posy[4] = {0,0,-1,1};

int board[1001][1001];
int vis[1001][1001];

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n,m;

    cin >> n >> m;

    for(int i = 0;i < n;i++){
        for(int j = 0;j < m;j++){
            cin >> board[i][j];
        }
    }

    for(int i = 0;i < n;i++){
        for(int j = 0;j < m;j++){
            if(board[i][j] == 0){
                for(int x = -1;x <= 1;x++){
                    for(int y = -1;y <= 1;y++){
                        int nx = i+x;
                        int ny = j+y;
                        if(nx < 0 || ny < 0 || nx >= n || ny >= m) continue;
                        if(board[nx][ny] != 1) continue;
                        board[nx][ny] = -1;
                    }
                }
            }
        }
    }

    queue<pair<int,int>>q;
    for(int i = 0;i < n;i++){
        if(board[i][0] <= 0) continue;
        q.push({i,0});
        vis[i][0] = 1;
    }

    int c = 0;
    while(1){
        int size_q = q.size();
        c++;
        if(size_q == 0){
            cout << -1;
            return 0;
        }

        while(size_q--){
            int x = q.front().first;
            int y = q.front().second;
            
            if(y == m-1){
                cout << c;
                return 0;
            }

            for(int i = 0;i < 4;i++){
                int nx = x + posx[i];
                int ny = y + posy[i];
                
                if(nx < 0 || ny < 0 || nx >= n || ny >= m) continue;
                if(vis[nx][ny] || board[nx][ny] <= 0) continue;
                
                vis[nx][ny] = 1;
                q.push({nx,ny});
            }
            q.pop();
        }
    }
    

    return 0;
}