Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- #define ll long long
- #define nl "\n"
- void files(){
- ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL);
- #ifndef ONLINE_JUDGE
- freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);
- #endif
- }
- void solve(){
- int n,m; cin>>n>>m;
- vector<vector<int>> grid(n, vector<int>(m));
- for(int i=0;i<n;i++){
- for(int j=0;j<m;j++){
- char c; cin>>c;
- if(c=='#') grid[i][j] = 0;
- else if(c=='P') grid[i][j] = -1;
- else if(c=='.') grid[i][j] = 1;
- else grid[i][j] = c-'0';
- }
- }
- queue<pair<int,int>> q;
- // map<pair<int,int>,bool> vis;
- // set<pair<int,int>> vis;
- bool vis[n][m] = {false};
- for(int i=0;i<n;i++){
- for(int j=0;j<m;j++){
- if(grid[i][j]==-1){
- q.push({i,j});
- vis[i][j] = true;
- }
- }
- }
- while(!q.empty()){
- int x = q.front().first, y = q.front().second;
- q.pop();
- int nx = x,ny = y;
- if(grid[x][y] == -1) ny = y+1;
- else ny = y+grid[x][y];
- if(ny<m){
- if(grid[nx][ny]>0 && !vis[nx][ny]){
- vis[nx][ny] = true;
- q.push({nx,ny});
- }
- nx = x+(grid[x][y]==-1?1:grid[x][y]);
- if(nx<n and grid[nx][ny]>0 and !vis[nx][ny]){
- vis[nx][ny] = true;
- q.push({nx,ny});
- }
- nx = x-(grid[x][y]==-1?1:grid[x][y]);
- if(nx>=0 and grid[nx][ny]>0 and !vis[nx][ny]){
- vis[nx][ny] = true;
- q.push({nx,ny});
- }
- }
- }
- for(int i=0;i<n;i++){
- for(int j=0;j<m;j++){
- if(vis[i][j]) grid[i][j] = -1;
- vis[i][j] = false;
- }
- }
- for(int i=0;i<n;i++){
- if(grid[i][0]>0){
- q.push({i,0});
- vis[i][0] = true;
- }
- }
- int ans = 0;
- while(!q.empty()){
- int sz = q.size();
- while(sz--){
- int x = q.front().first, y = q.front().second;
- q.pop();
- if(y==m-1){
- cout<<ans<<nl;
- return;
- }
- int nx = x,ny = y+grid[x][y];
- if(ny<m){
- if(grid[nx][ny]>0 and !vis[nx][ny]){
- vis[nx][ny] = true;
- q.push({nx,ny});
- }
- nx = x+grid[x][y];
- if(nx<n and grid[nx][ny]>0 and !vis[nx][ny]){
- vis[nx][ny] = true;
- q.push({nx,ny});
- }
- nx = x-grid[x][y];
- if(nx>=0 and grid[nx][ny]>0 and !vis[nx][ny]){
- vis[nx][ny] = true;
- q.push({nx,ny});
- }
- }
- }
- ans++;
- }
- cout<<-1<<nl;
- }
- int main(){
- files();
- int t = 1;
- // cin>>t;
- while(t--) solve();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement