fork download
  1. from collections import deque
  2.  
  3. # BFS 함수
  4. def bfs(m, fuel, map_grid):
  5. # 시작점은 (m-1, 0), 끝점은 (0, m-1)
  6. start_x, start_y = m - 1, 0
  7. end_x, end_y = 0, m - 1
  8.  
  9. # 연료를 소모하며 방문한 곳을 기록할 배열
  10. visited = [[False] * m for _ in range(m)]
  11. visited[start_x][start_y] = True
  12.  
  13. # BFS에 사용할 큐 (현재 x, y 좌표와 남은 연료를 저장)
  14. queue = deque([(start_x, start_y, fuel)]) # (x, y, 남은 연료)
  15.  
  16. # 네 방향으로 이동
  17. directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] # 상, 하, 좌, 우
  18.  
  19. while queue:
  20. x, y, current_fuel = queue.popleft()
  21.  
  22. # 끝점에 도달하면 남은 연료 출력
  23. if (x, y) == (end_x, end_y):
  24. return current_fuel
  25.  
  26. # 현재 위치에서 이동
  27. for dx, dy in directions:
  28. nx, ny = x + dx, y + dy
  29.  
  30. if 0 <= nx < m and 0 <= ny < m and not visited[nx][ny]:
  31. required_fuel = map_grid[nx][ny]
  32. if current_fuel >= required_fuel:
  33. visited[nx][ny] = True
  34. queue.append((nx, ny, current_fuel - required_fuel))
  35.  
  36. return 0 # 끝점에 도달할 수 없다면 0 출력
  37.  
  38. # 입력 처리
  39. m = int(input()) # 맵 크기
  40. map_grid = []
  41.  
  42. for _ in range(m):
  43. map_grid.append(list(map(int, input().split())))
  44.  
  45. fuel = int(input()) # 재현이가 가지고 있는 연료
  46.  
  47. # BFS 수행
  48. result = bfs(m, fuel, map_grid)
  49.  
  50. # 결과 출력
  51. print(result)
  52.  
Success #stdin #stdout 0.09s 14116KB
stdin
5
1 1 1 1 5
1 1 1 1 1
2 2 2 2 4
3 3 3 2 2 
-1 1 1 2 4
10
stdout
0