https://www.acmicpc.net/problem/2178

내 코드
from collections import deque
import sys
input = sys.stdin.readline
def main():
n, m = map(int, input().split())
maze = [list(input().strip()) for _ in range(n)]
visited = [[False] * m for _ in range(n)]
bfs(maze, visited)
print(maze[n-1][m-1])
def bfs(graph, visited):
queue = deque()
queue.append((0, 0))
rows = len(graph)
cols = len(graph[0])
while queue:
x, y = queue.popleft()
if visited[x][y]:
continue
visited[x][y] = True
if x - 1 >= 0:
if graph[x-1][y] == '1' and not visited[x-1][y]:
queue.append((x-1, y))
# 현재 칸의 값(문자열을 정수로 변환 후) + 1을 기록
graph[x-1][y] = str(int(graph[x][y]) + 1)
if x + 1 < rows:
if graph[x+1][y] == '1' and not visited[x+1][y]:
queue.append((x+1, y))
graph[x+1][y] = str(int(graph[x][y]) + 1)
if y - 1 >= 0:
if graph[x][y-1] == '1' and not visited[x][y-1]:
queue.append((x, y-1))
graph[x][y-1] = str(int(graph[x][y]) + 1)
if y + 1 < cols:
if graph[x][y+1] == '1' and not visited[x][y+1]:
queue.append((x, y+1))
graph[x][y+1] = str(int(graph[x][y]) + 1)
if __name__ == "__main__":
main()
1. 다른 코드를 보니 방향을 리스트로 설정해서 쉽게 푸는 듯 하자 좋은 방법이다.
2. 예외처리를 try except로 하지 말고 if문으로 처리하는게 낫다.
풀이 시간

'알고리즘 > 백준' 카테고리의 다른 글
| 백준 4779번 : 칸토어 집합(S3) (0) | 2025.01.30 |
|---|---|
| 백준 11866번 : 요세푸스 문제 0(S4) (0) | 2025.01.29 |
| 백준 1193번 : 분수찾기(S5) (0) | 2025.01.29 |
| 백준 18870번 : 좌표 압축(S2) (0) | 2025.01.28 |
| 백준 10814번 : 나이순 정렬(S5) (0) | 2025.01.28 |