๊ณจ๋“œ4 : dp & DFS ๋ฌธ์ œ์ด๋‹ค.

ํ’€์ด

์ด๊ฒŒ.. ์ ‘๊ทผ ๋ฐฉ์‹์„ ์•ฝ๊ฐ„ ๋ฐ˜๋Œ€๋กœํ•ด์„œ ์˜ค๋ž˜๊ฑธ๋ ธ๋‹ค. ๋ฐ”ํ…€ ์—… ๋ฐฉ์‹์œผ๋กœ ์‚ฌ๊ณ ๋ฅผ ํ•˜์—ฌ, ๋งˆ์ง€๋ง‰ ์ง€์ ๊นŒ์ง€ ๊ฐ€๋Š”๋ฐ ์žˆ์–ด 4๋ฐฉํ–ฅ์˜ ๊ฒฝ๋กœ๋ฅผ ๋”ํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋‹ค. ๊ทธ๋Ÿฐ๋ฐ ๊ทธ๋ ‡๊ฒŒ ์ƒ๊ฐ์„ ํ•˜๋‹ˆ ์‰ฝ๊ฒŒ ์ ํ™”์‹์ด ๋– ์˜ค๋ฅด์ง€ ์•Š์•˜๋‹ค.

์ด๋Ÿด ๋•Œ๋Š” ์ผ๋‹จ ๊ธฐ๋ณธ์ ์ธ ๊ณจ์ž์ธ ๊ทธ๋ž˜ํ”„ ๋ฐฉ๋ฒ•์˜ ํ•ด๊ฒฐ๋ฐฉ์‹๋ถ€ํ„ฐ ์ถœ๋ฐœํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค. ์ฆ‰, ์ผ๋‹จ ์ด ๋ฌธ์ œ๋Š” DFS ํƒ์ƒ‰ ๋ฌธ์ œ๋ผ ์ƒ๊ฐํ•˜๋ฉด ํŽธํ•˜๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ 250000 ํฌ๊ธฐ์˜ ํŒ์ด๊ณ , ๊ทธ๋ƒฅ ํ•  ๊ฒฝ์šฐ ๋‹น์—ฐํžˆ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚  ๊ฒƒ์ด๋‹ค.

๊ทธ๋Ÿผ ์ผ๋‹จ ๊ธฐ๋ณธ์ ์ธ DFS๋Š” ์–ด๋–ค ๋ฐฉ์‹์ธ๊ฐ€? ํŠน์ • ์œ„์น˜์—์„œ ๋‹ค์Œ ์œ„์น˜๋ฅผ ๊ตฌํ•˜๊ณ , DFS๋ฅผ ๋‹ค์‹œ ๋Œ๋ฆฌ๋Š” ๋ฐฉ์‹์ด๋‹ค. ์—ฌ๊ธฐ์„œ ํžŒํŠธ๋ฅผ ์–ป์–ด์•ผ ํ•œ๋‹ค. ํ•ด๋‹น ์œ„์น˜์—์„œ์˜ ๊ฒฝ๋กœ๋Š” ๋‹ค์Œ ์œ„์น˜์—์„œ ๊ตฌํ•œ ๊ฒฝ๋กœ๋“ค์˜ ํ•ฉ์œผ๋กœ ๊ตฌ์„ฑ๋œ๋‹ค. ๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— ์ด๋Ÿฌํ•œ DFS์  ํ’€์ด ๋ฐฉ๋ฒ•์— dp๋ฅผ ์ ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ˆ˜์›”ํ•œ ํ’€์ด๋ฅผ ํ•  ์ˆ˜ ์žˆ๋‹ค.

๊ทธ ๋‹ค์Œ์€ ์‰ฝ๋‹ค. dp ๋ฅผ ์ ์šฉํ•˜์—ฌ, ์ด๋ฏธ ๋ฐฉ๋ฌธํ•œ ์œ„์น˜์ธ ๊ฒฝ์šฐ๋Š” ๋”ํ•ด์ฃผ๋Š” ๊ฒƒ์œผ๋กœ ์ถ”๊ฐ€์ ์ธ ์—ฐ์‚ฐ์„ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค. ๊ธฐ์–ตํ•˜์ž.

๊ทธ๋ฆฌ๊ณ  setrecursionlimit์€ ํ•จ์ˆ˜๋‹คโ€ฆ

Code

import sys
from pprint import pprint
 
sys.setrecursionlimit(int(1e6))
input = sys.stdin.readline
 
n, m = map(int, input().split())
graph = [list(map(int, input().split())) for _ in range(n)]
dp = [[-1 for _ in range(m)] for _ in range(n)]
d = [[1, 0], [0, 1], [-1, 0], [0, -1]]
 
# dp[i][j] = 4๋ฐฉํ–ฅ์—์„œ ๋ฐœ์ƒํ•˜๋Š” ๊ฐ€๋Šฅํ•œ ๊ฒฝ๋กœ์˜ ํ•ฉ(๋‹จ, graph[i][j] > graph์˜ ๋‹ค์Œ ๊ฒฝ๋กœ : ์ฆ‰, ๊ฐ€๋Šฅํ•œ ๊ฒฝ๋กœ)
 
 
def DFS(y, x):
    dp[y][x] = 0  # ํ•ด๋‹น ํ•จ์ˆ˜์˜ ํ˜ธ์ถœ ์ด์œ ๋Š”, ํ•ด๋‹น ์ง€์ ์œผ๋กœ ๋ถ€ํ„ฐ ๊ฒฝ๋กœ๋ฅผ ๊ตฌํ•˜๋ผ๋Š” ๊ฒƒ์ž„ : ๊ฒฝ๋กœ ๊ฐœ์ˆ˜๋Š” 0๊ฐœ์ผ ์ˆ˜ ์žˆ์Œ
    if y == n - 1 and x == m - 1:  # ๊ฒฝ๋กœ๋ฅผ ๊ตฌํ•˜๋ผ๊ณ  ํ–ˆ๋Š”๋ฐ ๋„์ฐฉ์ง€์ ์ด๋ฉด ๊ฒฝ๋กœ๋ฅผ 1๋กœ ์—…๋ฐ์ดํŠธ ํ•ด์คŒ
        dp[y][x] = 1
        return dp[y][x]
 
    for dy, dx in d:
        ny, nx = y + dy, x + dx
        if 0 <= ny < n and 0 <= nx < m and graph[y][x] > graph[ny][nx]:
            if dp[ny][nx] == -1:  # ์•„์ง ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์•˜๋‹ค๋ฉด,
                dp[ny][nx] = DFS(ny, nx)
            dp[y][x] += dp[ny][nx]  # ์ด๋ฏธ ๋ฐฉ๋ฌธํ•ด์„œ ํƒ์ƒ‰์„ ์™„๋ฃŒํ–ˆ๋‹ค๋ฉด, ๊ทธ๋Œ€๋กœ ๋”ํ•ด์คŒ
    return dp[y][x]
 
print(DFS(0, 0))

Reference