3 solutions
-
2
#include<bits/stdc++.h> using namespace std; struct tod { int x,y; }; int n,sx,sy,ex,ey; const int nm=103; char g[nm][nm]; int dist[nm][nm]; int dx[]={-1,1,0,0}; int dy[]={0,0,-1,1}; bool check(int x,int y) { if(x<1||x>n||y<1||y>n|| g[x][y]=='x') return 0; return 1; } int bfs() { queue<tod> u; u.push({sx,sy}); while(u.size()){ tod t=u.front(); u.pop(); if(t.x==ex&&t.y==ey){ return dist[ex][ey]; } for(int i=0;i<4;i++){ int a=t.x+dx[i]; int b=t.y+dy[i]; while(check(a,b)){ if(dist[a][b]>dist[t.x][t.y]+1){ dist[a][b]=dist[t.x][t.y]+1; u.push({a,b}); } a+=dx[i]; b+=dy[i]; } } } return 0; } int main() { cin>>n; for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ cin>>g[i][j]; if(g[i][j]=='A'){ sx=i; sy=j; } else if(g[i][j]=='B'){ ex=i; ey=j; } } } memset(dist,0x3f,sizeof dist); dist[sx][sy]=0; bfs(); if(dist[ex][ey]==0x3f3f3f3f) cout<<-1; else cout<<dist[ex][ey]-1; return 0; }
Information
- ID
- 227
- Time
- 1000ms
- Memory
- 256MiB
- Difficulty
- 5
- Tags
- # Submissions
- 29
- Accepted
- 11
- Uploaded By