๐๏ธ Algorithm/๐ฉ ๋ฐฑ์ค
๐ฉ [๋ฐฑ์ค] [Python] [Gold5] 17070๋ฒ_ํ์ดํ ์ฎ๊ธฐ๊ธฐ 1
Dbswnstjd
2023. 5. 1. 14:33
๋ฌธ์
https://www.acmicpc.net/problem/17070
17070๋ฒ: ํ์ดํ ์ฎ๊ธฐ๊ธฐ 1
์ ํ์ด๊ฐ ์ ์ง์ผ๋ก ์ด์ฌํ๋ค. ์ ์ง์ ํฌ๊ธฐ๋ N×N์ ๊ฒฉ์ํ์ผ๋ก ๋ํ๋ผ ์ ์๊ณ , 1×1ํฌ๊ธฐ์ ์ ์ฌ๊ฐํ ์นธ์ผ๋ก ๋๋์ด์ ธ ์๋ค. ๊ฐ๊ฐ์ ์นธ์ (r, c)๋ก ๋ํ๋ผ ์ ์๋ค. ์ฌ๊ธฐ์ r์ ํ์ ๋ฒํธ, c๋ ์ด์
www.acmicpc.net
ํ์ด
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()