어제 배운 그래프 형태를 이용해 보려고 했다.
깊이 우선이냐 너비 우선이냐 고민
너비 우선으로 결정
height, width = map(int, input().split())
maps = [list(map(int, input())) for _ in range(height)]
li = [(0, 1), (1, 0), (0, -1), (-1, 0)]
graph = {x : [] for x in range(width*height)}
for i in range(width*height):
좌표 = (i//width, i%width)
if maps[좌표[0]][좌표[1]] == 0:
continue
for j in li:
next_좌표 = (좌표[0]+j[0] , 좌표[1]+j[1])
if -1 in next_좌표 or width <= next_좌표[1] or height <= next_좌표[0] or maps[next_좌표[0]][next_좌표[1]] == 0:
continue
graph[i].append(next_좌표[0]*width + next_좌표[1])
def bfs():
visited, need_visit = list(), list([0,'x'])
count = 1
while (len(need_visit) != 1 or need_visit[0] != 'x'):
x = need_visit.pop(0)
if x == "x":
count += 1
need_visit.append('x')
continue
if x in visited:
continue
if x == width*height-1:
break
visited.append(x)
need_visit.extend(graph[x])
return count
print(bfs())
from collections import deque
n, m = map(int, input().split())
maps = [ list(map(int, input())) for _ in range(n) ]
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
queue = deque()
count = 0
def bfs(x,y):
queue.append([x,y])
while queue:
x, y = queue.popleft()
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < n and 0 <= ny < m and maps[nx][ny] == 1:
maps[nx][ny] = maps[x][y] + 1
queue.append([nx, ny])
return maps[n-1][m-1]
print(dfs(0,0))