코테 백준 2178 실버1

김동윤·2023년 8월 2일
0
post-thumbnail

백준 2178

이문제도 이전의 bfs문제와 같이 동서남북 배열을 이용하고 que가 빌때까지 반복문을 이용해서 1이면 graph[x][y]의 값을 1증가해주어 최종적으로 graph[n-1][m-1]의 값을 구해주면된다. 백준 1926보다 쉬운점은 bfs(0,0)을 시행만하면된다는점이다.

import sys
from collections import deque
input=sys.stdin.readline

n,m=map(int,input().split())
graph=[]

for _ in range(n):
    graph.append(list(map(int,input().rstrip())))

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

def bfs(graph,i,j):
    que=deque()
    que.append((i,j))
    while que:
        a,b=que.popleft()
        for i in range(4):
            x=a+dx[i]
            y=b+dy[i]
            
            if x<0 or y<0 or x>n-1 or y>m-1:
                continue
            if graph[x][y]==0:
                continue
            if graph[x][y]==1:
                que.append((x,y))
                graph[x][y]=graph[a][b]+1
    return graph[n-1][m-1]

print(bfs(graph,0,0))
profile
Back-End

0개의 댓글