• toc {:toc}

문제 ν™•μΈν•˜κΈ°

풀이

μ΄μ›ƒν•œ 곳으둜 μ΄λ™ν•˜λ©΄μ„œ λͺ©ν‘œ μ§€μ κΉŒμ§€ μ΄λ™ν•˜λŠ” 문제둜, DFS 와 DP λ₯Ό μ„žμ–΄μ€˜μ•Ό μ‹œκ°„μ΄ˆκ³Όμ—†μ΄ 문제λ₯Ό 풀이할 수 μžˆλ‹€.

μ²˜μŒμ—λŠ” stack 을 μ΄μš©ν•΄ bottom-up 으둜 λ§ˆμ§€λ§‰μ— λ„μ°©ν•˜λŠ” 횟수λ₯Ό μΉ΄μš΄νŠΈν•˜μ—¬ ν’€μ΄ν•˜λ € ν–ˆμ§€λ§Œ, λ‹€μŒμ˜ κ²½μš°μ—λŠ” μ€‘λ³΅λœ 길을 μ§€λ‚˜λŠ” κ²½μš°κ°€ λ§Žμ•„μ§ˆ 수 있기 λ•Œλ¬Έμ— μ‹œκ°„μ΄ˆκ³Όμ— 걸리게 λœλ‹€.

λ•Œλ¬Έμ— λ„μ°©μ§€μ μ—μ„œ μ—­μœΌλ‘œ 이동할 수 μžˆλŠ” 횟수λ₯Ό μΉ΄μš΄νŠΈν•˜λ©΄μ„œ 처음 μ‹œμž‘μ§€μ κΉŒμ§€ 도달할 수 μžˆλ„λ‘ μ„€μ •ν•˜λ©΄ μ‹œμž‘μ§€μ μ—μ„œ λ„μ°©μ§€μ κΉŒμ§€ 이동할 수 μžˆλŠ” 횟수λ₯Ό 카운트 ν•  수 μžˆλ‹€.

μž…λ ₯ λ°°μ—΄

image

dist λ°°μ—΄

image

1 인 κ²½μš°μ—λŠ” λ„μ°©μ§€μ μ—μ„œ ν•΄λ‹Ή μœ„μΉ˜κΉŒμ§€ μ˜€λŠ” 방식이 1 개만 μ‘΄μž¬ν•œλ‹€λŠ” μ˜λ―Έμ΄λ‹€.

#include <bits/stdc++.h>
using namespace std;
#define X first
#define Y second
 
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
int board[501][501] = {0,};
int dist[501][501];
int M, N, res = 0;
 
int dfs(int X, int Y){
    if(X == M-1 && Y == N-1){
        return 1;
    }
    if(dist[X][Y] == -1){
        dist[X][Y] = 0;
        for(int dir = 0; dir < 4; dir++){
            int nx = X + dx[dir];
            int ny = Y + dy[dir];
            if(nx < 0 || nx >= M || ny < 0 || ny >= N) continue;
            if(board[X][Y] <= board[nx][ny]) continue;
            dist[X][Y] += dfs(nx, ny);
        }
 
    }
    return dist[X][Y];
}
 
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
 
 
    cin >> M >> N;
 
    for(int row = 0; row < M; row++){
        for(int col = 0; col < N; col++){
            cin >> board[row][col];
            dist[row][col] = -1;
        }
    }
 
 
    cout << dfs(0, 0) << '\n';
 
 
    return 0;
}