๋ฌธ์
https://www.acmicpc.net/problem/17070
ํ์ด
import sys
count = 0
N = int(input())
home = []
for _ in range(N):
home.append([int(x) for x in sys.stdin.readline().rstrip().split()])
def dfs(x,y,state): # state 0: ๊ฐ๋ก, 1: ์ธ๋ก , 2: ๋๊ฐ์
global count
if x == N - 1 and y == N - 1:
count += 1
return
if state == 0:
if y == N - 1: # ์ด๋๋ถ๊ฐ
return
if 0 <= x < N and 0 <= y + 1 < N and home[x][y + 1] == 0:
dfs(x, y + 1, 0)
if 0 <= x + 1 < N and 0 <= y + 1 < N and home[x][y + 1] == 0 and home[x + 1][y] == 0 and home[x + 1][
y + 1] == 0:
dfs(x + 1, y + 1, 2)
elif state == 1:
if x == N - 1: # ์ด๋๋ถ๊ฐ
return
if 0 <= x + 1 < N and 0 <= y < N and home[x + 1][y] == 0:
dfs(x + 1, y, 1)
if 0 <= x + 1 < N and 0 <= y + 1 < N and home[x][y + 1] == 0 and home[x + 1][y] == 0 and home[x + 1][
y + 1] == 0:
dfs(x + 1, y + 1, 2)
elif state == 2:
if 0 <= x < N and 0 <= y + 1 < N and home[x][y + 1] == 0:
dfs(x, y + 1, 0)
if 0 <= x + 1 < N and 0 <= y < N and home[x + 1][y] == 0:
dfs(x + 1, y, 1)
if 0 <= x + 1 < N and 0 <= y + 1 < N and home[x][y + 1] == 0 and home[x + 1][y] == 0 and home[x + 1][
y + 1] == 0:
dfs(x + 1, y + 1, 2)
dfs(0,1,0)
print(count)
๋งจ ์ฒ์ DFS๋ฅผ ํตํด ํ์๋ค. ๊ทผ๋ฐ ์๊ฐ์ด๊ณผ๊ฐ ๋ฐ์ํด์ pypy3 ๋ก ํ์๋๋ฐ ํต๊ณผํ์๋ค.
๊ทธ๋์ ์ฐพ์๋ณธ ๊ฒฐ๊ณผ DP ๋ฅผ ํตํด ํ ์ ์๋ ๋ฌธ์ ์๋ค.
# ๋ฐฑ์ค 17070๋ฒ ๋ฌธ์ - ํ์ดํ ์ฎ๊ธฐ๊ธฐ 1
def solution():
dp[0][0][1] = 1
for i in range(2, n):
if graph[0][i] == 0:
dp[0][0][i] = dp[0][0][i - 1]
for r in range(1, n):
for c in range(1, n):
if graph[r][c] == 0 and graph[r][c - 1] == 0 and graph[r - 1][c] == 0:
dp[1][r][c] = dp[0][r - 1][c - 1] + dp[1][r - 1][c - 1] + dp[2][r - 1][c - 1]
if graph[r][c] == 0:
dp[0][r][c] = dp[0][r][c - 1] + dp[1][r][c - 1]
dp[2][r][c] = dp[2][r - 1][c] + dp[1][r - 1][c]
print(sum(dp[i][n - 1][n - 1] for i in range(3)))
n = int(input())
graph = [list(map(int, input().split())) for _ in range(n)]
dp = [[[0 for _ in range(n)] for _ in range(n)] for _ in range(3)]
solution()
'๐๏ธ Algorithm > ๐ฉ ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐ฉ [๋ฐฑ์ค] [Python] [Gold5] 2096๋ฒ_๋ด๋ ค๊ฐ๊ธฐ (2) | 2023.05.03 |
---|---|
๐ฉ [๋ฐฑ์ค] [Python] [Silver1] 11057๋ฒ_์ค๋ฅด๋ง ์ (2) | 2023.05.02 |
๐ฉ [๋ฐฑ์ค] [Python] [Gold5] 2470๋ฒ_๋ ์ฉ์ก (0) | 2023.04.30 |
๐ฉ [๋ฐฑ์ค] [Python] [Gold5] 2565๋ฒ_์ ๊น์ค (0) | 2023.04.29 |
๐ฉ [๋ฐฑ์ค] [Python] [Gold3] 2638๋ฒ_์น์ฆ (1) | 2023.04.28 |