미로탈출 : DFS&BFS

주리·2022년 12월 1일
0

코테_DFS&BFS

목록 보기
2/2
post-thumbnail

main 메소드 로직

  1. from collections import dequeue
  2. n,m,grpah[][] 입력받기
  3. print(bfs(0,0)) 호출 (가장아래줄)
    [0,0]에서 상하좌우
    X = [0,0,-1,1]
    Y = [1,-,1,0,0]
    상 하 좌 우

def bfs(x,y) 로직

  1. queue 큐를 만들기 (deque로)
  2. graph[x][y]를 append
  3. while (queue) : 큐가 빌때까지
    popleft--> x,y

코드

  • 아직 BFS 를 어떻게 짜야하는지 잘 감이 안온다,,
  상하좌우 for i in range 4:
    nx = x + X[i]
    ny = y + Y[i]

    if nx<0 or ny<0 or nx>=n or ny>=m :
      continue
    if graph[nx][y]==1:
      continue
    if graph[nx][ny]==0:
      graph[nx][ny] = graph[x][y] + 1

  return g[n-1][m-1]
    
'''

from collections import deque

X=[0,0,-1,1]
Y=[1,-1,0,0]
# 상 하 좌 우

n,m = map(int, input().split())
graph=[]
for i in range(n):
  graph.append(list(map(int,input().split())))

def bfs(x,y):
  #deque()를 이용해서 큐를 만든다
  queue = deque()
  queue.append((x,y))

  while queue :
    x,y = queue.popleft()
    for i in range(4):
      nx= x + X[i]
      ny= y + Y[i]

      if nx<0 or ny<0 or nx>=n or ny>=m :
        continue
      if graph[nx][ny]==0:
        continue

      if graph[nx][ny]==1:
        graph[nx][ny] = graph[x][y] + 1
        queue.append((nx,ny))
  return graph[n-1][m-1]
print(bfs(0,0))
~~~
profile
완벽한 글 보다, 그 과정들을 기록하는 개발자

0개의 댓글