[baekjoon] 2178 미로 탐색 실버1

윤주원·2024년 12월 11일
0

baekjoon

목록 보기
10/13
post-thumbnail

백준 BFS 문제
링크 : https://www.acmicpc.net/problem/2178

설명

  • BFS 기본 문제라고 볼 수 있다.
  • 전체적인 틀은 개념과 거의 비슷하다.

코드

from collections import deque

n,m = map(int,input().split())
arr= [list(map(int,input())) for _ in range(n)]

dx = [1,-1,0,0]
dy = [0,0,1,-1]

def BFS(x,y):
    
    q = deque()
    q.append([x,y])
    while q:
        x,y = q.popleft()
        for i in range(4):
            nx = x+dx[i]
            ny = y+dy[i]
            if 0<= nx < n and 0<=ny <m:
                if arr[nx][ny] == 1:
                    arr[nx][ny] +=arr[x][y]
                    q.append([nx,ny])
    return arr[n-1][m-1]

print(BFS(0,0))

깨달은점

  • 처음 if문 안 코드를 arr[nx][ny] +=1 이라고 했는데, 출력이 2가 나와서 잘못되었다고 생각함.
  • arr[nx][ny] +=arr[x][y]로 수정하며 이전 경로의 값을 더해주는 것으로 수정함.
  • 다른 코드에서는 arr[nx][ny] =arr[x][y]+1로 했음.
profile
안녕하세요

0개의 댓글