https://www.acmicpc.net/problem/1520
단순히 DFS 완전탐색으로 풀었지만 메모리 초과가 난다. 이유는
완전탐색DFS의 경우, 각 칸에서 최악의경우 O(N x M)번의 탐색을 해야한다.
각 칸을 여러 번 중복해서 탐색할 수 있기 때문에, 최악의 경우 각 칸에 대해 O(N×M) 수행을 한다. 총 칸수는 N x M개이기 때문에
O((N x M) x (N x M)))의 시간 복잡도가 발생하게 된다.
즉 , 최악의경우 500 * 500 * 500 * 500 = 62,500,000,000 => 625억 이므로, 제한시간인 2초를 1초에 1억이라고 했을때
625억 >> 2억이므로 (625초 >> 2초)
당연히 시간초과(혹은 스택이 무한적 쌓이므로 메모리 초과)가 난다.
이 문제는 dfs를 이용한 dp 메모이 제이션을 해야한다.
dp[x][y]를 (x,y)에서, 도착점까지의 경로의 수라고 생각한다면,
각 dp[x][y]가 존재하는경우엔, 굳이 그 똑같은 경로를 dfs로 한번 다시 탐색할 필요가 없어진다.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
static int N;
static int M;
static int[][] map;
static int[][] dp;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] lines = br.readLine().split(" ");
N = Integer.parseInt(lines[0]);
M = Integer.parseInt(lines[1]);
dp = new int[N][M];
map = new int[N][M];
for (int i = 0; i < N; i++) {
lines = br.readLine().split(" ");
for (int j = 0; j < M; j++) {
map[i][j] = Integer.parseInt(lines[j]);
dp[i][j] = -1;
}
}
System.out.println(dfs(new Point(0, 0)));
}
static int[] dx = {-1, 0, 1, 0};
static int[] dy = {0, 1, 0, -1};
static int dfs(Point p) {
int x = p.x;
int y = p.y;
int weight = map[x][y];
if (x == N - 1 && y == M - 1) {
return 1;
}
dp[x][y] = 0;
for (int i = 0; i < 4; i++) {
int nextX = x + dx[i];
int nextY = y + dy[i];
if (nextX < 0 || nextX >= N || nextY < 0 || nextY >= M || weight <= map[nextX][nextY]) continue;
if (dp[nextX][nextY] == -1) {
dp[x][y] += dfs(new Point(nextX, nextY));
} else {
dp[x][y] += dp[nextX][nextY];
}
}
return dp[x][y];
}
}
class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "(" + x + "," + y + ")";
}
}
'PS > 다이나믹프로그래밍' 카테고리의 다른 글
[JAVA] 백준 1890 - 점프 (0) | 2024.10.16 |
---|---|
[JAVA] 백준 1446 - 지름길 (0) | 2024.10.15 |
[JAVA] 백준 12865 - 평범한 배낭 (0) | 2024.06.21 |
[JAVA] 백준 2096 - 내려가기 (1) | 2024.06.06 |
[JAVA] 백준 16928 - 뱀과 사다리 게임 (0) | 2024.04.05 |