fork download
  1. # your code goes here
  2. from collections import deque
  3. import sys
  4.  
  5. r, c = map(int, sys.stdin.readline().split())
  6. graph = [] * r
  7. for _ in range(r):
  8. graph.append(list(map(str, sys.stdin.readline().rstrip())))
  9. visited = [[False] * c for _ in range(r)]
  10.  
  11.  
  12. # 탈출 가능한지
  13. def goout(x, y):
  14. if x == 0 or x == r - 1 or y == 0 or y == c - 1:
  15. return True
  16. else:
  17. return False
  18.  
  19.  
  20. dx = [-1, 1, 0, 0]
  21. dy = [0, 0, -1, 1]
  22.  
  23.  
  24. def fire_extend(fire):
  25. new_fire = deque()
  26. while fire:
  27. x, y = fire.popleft()
  28. for j in range(4):
  29. nx = x + dx[j]
  30. ny = y + dy[j]
  31. if 0 <= nx < r and 0 <= ny < c:
  32. if graph[nx][ny] != '#':
  33. graph[nx][ny] = 'F'
  34. new_fire.append([nx, ny])
  35. visited[nx][ny] = True
  36. return new_fire
  37.  
  38.  
  39. q = deque()
  40. start = []
  41. fire = deque()
  42. for i in range(r):
  43. for j in range(c):
  44. if graph[i][j] == 'J':
  45. start = [i, j]
  46. visited[i][j] = True
  47. if graph[i][j] == 'F':
  48. fire.append([i, j])
  49. visited[i][j] = True
  50. q.append(start)
  51. answer = 1
  52. while q:
  53. x, y = q.popleft() # 현재 위치
  54. visited[x][y] = True
  55. fire = fire_extend(fire)
  56. if goout(x, y):
  57. print(answer)
  58. exit(0)
  59. for i in range(4):
  60. nx = x + dx[i]
  61. ny = y + dy[i]
  62. if not visited[nx][ny]:
  63. if 0 <= nx < r and 0 <= ny < c:
  64. if graph[nx][ny] == '.':
  65. q.append((nx, ny))
  66. visited[nx][ny] = True
  67. answer += 1
  68. # print(graph)
  69. print('IMPOSSIBLE')
  70.  
Success #stdin #stdout 0.04s 9544KB
stdin
6 5
##.##
#...#
#...#
#...#
#J..#
#####
stdout
12