fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int INF = 987654321;
  4. int r, c, fire[1004][1004], jh[1004][1004], yi, xi, y, x, ret;
  5. char a[1004][1004];
  6. queue<pair<int, int>> q;
  7. int dy[] = {-1, 0, 1, 0};
  8. int dx[] = {0, 1, 0, -1};
  9.  
  10. int main(){
  11. fill(&fire[0][0], &fire[0][0] + 1004 * 1004, INF);
  12. cin >> r >> c;
  13. for(int i = 0; i < r; i++){
  14. for(int j = 0; j < c; j++){
  15. cin >> a[i][j];
  16. if(a[i][j] == 'F'){
  17. q.push({i, j});
  18. fire[i][j] = 1;
  19. } else if(a[i][j] == 'J'){
  20. yi = i, xi = j;
  21. }
  22. }
  23. }
  24.  
  25. while(q.size()){
  26. tie(y, x) = q.front();
  27. q.pop();
  28. for(int i = 0; i < 4; i++){
  29. int ny = y + dy[i];
  30. int nx = x + dx[i];
  31. if(ny < 0 || ny >= r || nx < 0 || nx >= c || fire[ny][nx] != INF || a[ny][nx] == '#') continue;
  32. fire[ny][nx] = fire[y][x] + 1;
  33. q.push({ny, nx});
  34. }
  35. }
  36.  
  37. q.push({yi, xi});
  38. while(q.size()){
  39. tie(y, x) = q.front();
  40. q.pop();
  41.  
  42. if(y == 0 || y == r - 1 || x == 0 || x == c - 1){
  43. ret = jh[y][x];
  44. break;
  45. }
  46.  
  47. for(int i = 0; i < 4; i++){
  48. int ny = y + dy[i];
  49. int nx = x + dx[i];
  50. if(ny < 0 || ny >= r || nx < 0 || nx >= c || jh[ny][nx] || a[ny][nx] == '#') continue;
  51. if(fire[ny][nx] <= jh[y][x] + 1) continue;
  52. jh[ny][nx] = jh[y][x] + 1;
  53. q.push({ny, nx});
  54. }
  55. }
  56. if(ret != 0) cout << ret << '\n';
  57. else cout << "IMPOSSIBLE\n";
  58. }
Success #stdin #stdout 0.01s 10196KB
stdin
4 4
####
#JF#
#..#
#..#
stdout
2