-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
13-SeongHoonC #49
13-SeongHoonC #49
Conversation
Visited 배열 대신 거리 기록용 Distances 배열을 이용하는 것도 괜찮아 보이네요.
이 상태에서 BFS를 수행하며 원본 지도는 건드리지 않고 단순히 "갈 수 있는 지" 검사하는 용도로만 사용하는 겁니다. 방문 체크의 경우 Distances 배열의 값이 -1이 아니면 이전에 방문했음을 알 수 있으니까 해결 가능합니다. from collections import deque
input = open(0).readline
n, m = map(int, input().split())
board = [list(map(int, input().split())) for _ in range(n)]
distances = [[-1] * m for _ in range(n)] # 초기값은 -1
q = deque()
for i in range(n):
for j in range(m):
if board[i][j] == 2: # 시작점
distances[i][j] = 0
q.append((i, j))
elif board[i][j] == 0: # 갈 수 없는 영역
distances[i][j] = 0
offset = [(-1, 0), (0, 1), (1, 0), (0, -1)]
def out_of_bound(x: int, y: int) -> int:
return not (0 <= x < n and 0 <= y < m)
while q:
x, y = q.popleft()
for dx, dy in offset:
nx, ny = x + dx, y + dy
# 범위를 벗어났거나, 갈 수 있는 곳이 아니거나, 이미 방문했던 곳이라면 가지 않음
if out_of_bound(nx, ny) or board[nx][ny] != 1 or distances[nx][ny] != -1:
continue
distances[nx][ny] = distances[x][y] + 1 # (x, y)에서 한 칸 더 감
q.append((nx, ny))
print('\n'.join([' '.join(map(str, row)) for row in distances])) # distances 배열에 담긴 값 모두 출력 |
저도 그래프를 visited를 따로 만들지 않고 위에 교황님이 말했던 것 처럼
from collections import deque
dx = [0,0,-1,1]
dy = [1,-1,0,0]
n, m = map(int, input().split())
graph = []
visited = [[-1] * m for _ in range(n)]
for _ in range(n):
graph.append(list(map(int, input().split())))
for i in range(n):
for j in range(m):
if graph[i][j] == 2:
first_x,first_y = j, i
queue = deque()
queue.append([first_x, first_y])
visited[first_y][first_x] = 0
while queue:
x, y = queue.popleft()
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if nx >= m or nx < 0 or ny >= n or ny < 0:
continue
if visited[ny][nx] == -1 and graph[ny][nx] == 1:
visited[ny][nx] = visited[y][x] + 1
queue.append([nx,ny])
for i in range(n):
for j in range(m):
if graph[i][j] == 0:
print(0, end = " ")
else :
print(visited[i][j], end =" ")
print() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
from collections import deque
import sys
input = sys.stdin.readline
N,M = map(int, input().split())
queue = deque()
_map = []
visited = [[False] * M for _ in range(N)]
result = [[-1]*M for _ in range(N)]
for i in range(N):
row = list(map(int, input().split()))
for j in range(M):
if row[j] == 2 :
queue.append((i,j))
visited[i][j] = True
result[i][j] = 0
if row[j] == 0 :
result[i][j] = 0
_map.append(row)
direction = [(1,0), (-1,0), (0,1), (0,-1)]
while queue :
x,y = queue.popleft()
for dx, dy in direction :
move_x, move_y = x+dx, y+dy
if 0<=move_x < N and 0<=move_y < M and visited[move_x][move_y] == False and _map[move_x][move_y] :
queue.append((move_x, move_y))
visited[move_x][move_y] = True
result[move_x][move_y] = result[x][y] + 1
for row in result :
for i in row :
print (i, end=' ')
print()
BFS 문제 더욱 많이 풀어봐야겠어요..! 이 문제 풀어보면서 헷갈렸던 부분이 어떤 조건에서 queue를 집어넣어야 하는지 였습니다.
🔗 문제 링크
쉬운 최단거리
✔️ 소요된 시간
1시간 30분
graph 하나만 써서 해보려고 했는데 포기하고 visited 배열 하나 더 생성해서 푼다고 시간이 오래걸렸네용
✨ 수도 코드
📚 새롭게 알게된 내용