https://www.acmicpc.net/problem/1405

백트래킹을 사용해 모든 경로를 구한다.
4 방향에 대해 다음 좌표를 정한다. 확률이 0인 방향은 제외한다.
만약 현재 좌표가 범위밖이거나 방문했던 좌표라면 건너뛴다.
dfs를 통해 탐색한 모든 경로는 단순한 경로임이 보장된다.
import sys
input = sys.stdin.readline
arr = list(map(int, input().split()))
n = arr[0]
p = [x/100 for x in arr[1:]]
visited = [[False for _ in range(2*n+1)] for _ in range(2*n+1)]
answer = 0
def dfs(cx,cy,route,prob):
global answer
if route == n:
answer += prob
return
d = [[0,1],[0,-1],[1,0],[-1,0]]
for i in range(4):
if p[i] == 0:
continue
dx,dy = d[i]
nx, ny = cx+dx, cy+dy
if nx<0 or nx>2*n or ny<0 or ny>2*n or visited[nx][ny]:
continue
visited[nx][ny] = True
dfs(nx,ny,route+1,prob*p[i])
visited[nx][ny] = False
visited[n][n] = True
dfs(n,n,0,1)
print(answer)

'python' 카테고리의 다른 글
| [백준] 1700 멀티탭 스케줄링, python (0) | 2025.10.03 |
|---|---|
| [백준] 1600 말이 되고픈 원숭이, python (0) | 2025.10.03 |
| [백준] 1103 게임, python (0) | 2025.10.03 |
| [백준] 1079 마피아, python (0) | 2025.10.03 |
| [백준] 1016 제곱 ㄴㄴ 수, python (0) | 2025.10.03 |