https://www.acmicpc.net/problem/14248
코드
from collections import deque
n = int(input())
a = list(map(int, input().split()))
start = int(input())-1
q = deque([start])
visited = [False]*n
visited[start] = True
ans = 1
while q:
now = q.popleft()
# 왼쪽, 오른쪽
for nx in [now-a[now], now+a[now]]:
if 0 <= nx < n and not visited[nx]:
visited[nx] = True
q.append(nx)
ans += 1
print(ans)
단순히 각 돌에 방문할 수 있는지 여부만 판단하면 되기 때문에 BFS를 이용하여 갈 수 있는 돌들을 방문하며 개수를 세면 된다.
'문제풀이 > DFS_BFS' 카테고리의 다른 글
[Python/파이썬] 백준 2589번 보물섬 (0) | 2024.05.21 |
---|---|
[Python/파이썬] 백준 6118번 숨바꼭질 (0) | 2024.05.14 |
[Python/파이썬] 백준 1303번 전쟁 - 전투 (0) | 2024.04.22 |
[Python/파이썬] 백준 15644번 구슬 탈출 3 (0) | 2024.04.21 |
[Python/파이썬] 백준 17616번 등수 찾기 (0) | 2024.04.18 |
https://www.acmicpc.net/problem/14248
코드
from collections import deque n = int(input()) a = list(map(int, input().split())) start = int(input())-1 q = deque([start]) visited = [False]*n visited[start] = True ans = 1 while q: now = q.popleft() # 왼쪽, 오른쪽 for nx in [now-a[now], now+a[now]]: if 0 <= nx < n and not visited[nx]: visited[nx] = True q.append(nx) ans += 1 print(ans)
단순히 각 돌에 방문할 수 있는지 여부만 판단하면 되기 때문에 BFS를 이용하여 갈 수 있는 돌들을 방문하며 개수를 세면 된다.
'문제풀이 > DFS_BFS' 카테고리의 다른 글
[Python/파이썬] 백준 2589번 보물섬 (0) | 2024.05.21 |
---|---|
[Python/파이썬] 백준 6118번 숨바꼭질 (0) | 2024.05.14 |
[Python/파이썬] 백준 1303번 전쟁 - 전투 (0) | 2024.04.22 |
[Python/파이썬] 백준 15644번 구슬 탈출 3 (0) | 2024.04.21 |
[Python/파이썬] 백준 17616번 등수 찾기 (0) | 2024.04.18 |