[백준/Python] 2178번 - 미로 탐색

Sujin Lee·2022년 9월 30일
0

코딩테스트

목록 보기
122/172
post-thumbnail

문제

백준 2178번 - 미로 탐색

해결 과정

시행착오

import sys

n,m = map(int,sys.stdin.readline().split())

graph = [sys.stdin.readline().strip() for _ in range(n)]

dx = [-1,1,0,0]
dy = [0,0,-1,1]
visited = [[False] * m for _ in range(n)]
cnt = 0

ans = []
from collections import deque
def bfs(x,y):
  global cnt
  q = deque([(x,y)])
  visited[x][y] = True
  
  while q:
    a,b = q.popleft()
    if a == n-1 and b == m-1:
      break
    for i in range(4):
      nx = a + dx[i]
      ny = b + dy[i]
      if 0 <= nx < n and 0 <= ny < m:
        if graph[nx][ny] == '1'and not visited[nx][ny]:
          cnt += 1
          q.append([nx,ny])
          visited[nx][ny] = True

bfs(0,0)
print(cnt)

풀이

import sys
from collections import deque

n,m = map(int,sys.stdin.readline().split())
graph = []

for _ in range(n):
  graph.append(list(map(int,sys.stdin.readline().strip())))

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


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

bfs(0,0)
print(graph[n-1][m-1])
profile
공부한 내용을 기록하는 공간입니다. 📝

0개의 댓글