[Gold III] 내리막 길 - 1520
성능 요약
메모리: 198548 KB, 시간: 928 ms
분류
깊이 우선 탐색(dfs), 다이나믹 프로그래밍(dp), 그래프 이론(graphs), 그래프 탐색(graph_traversal)
문제 설명
여행을 떠난 세준이는 지도를 하나 구하였다. 이 지도는 아래 그림과 같이 직사각형 모양이며 여러 칸으로 나뉘어져 있다. 한 칸은 한 지점을 나타내는데 각 칸에는 그 지점의 높이가 쓰여 있으며, 각 지점 사이의 이동은 지도에서 상하좌우 이웃한 곳끼리만 가능하다.
현재 제일 왼쪽 위 칸이 나타내는 지점에 있는 세준이는 제일 오른쪽 아래 칸이 나타내는 지점으로 가려고 한다. 그런데 가능한 힘을 적게 들이고 싶어 항상 높이가 더 낮은 지점으로만 이동하여 목표 지점까지 가고자 한다. 위와 같은 지도에서는 다음과 같은 세 가지 경로가 가능하다.
지도가 주어질 때 이와 같이 제일 왼쪽 위 지점에서 출발하여 제일 오른쪽 아래 지점까지 항상 내리막길로만 이동하는 경로의 개수를 구하는 프로그램을 작성하시오.
입력
첫째 줄에는 지도의 세로의 크기 M과 가로의 크기 N이 빈칸을 사이에 두고 주어진다. 이어 다음 M개 줄에 걸쳐 한 줄에 N개씩 위에서부터 차례로 각 지점의 높이가 빈 칸을 사이에 두고 주어진다. M과 N은 각각 500이하의 자연수이고, 각 지점의 높이는 10000이하의 자연수이다.
출력
첫째 줄에 이동 가능한 경로의 수 H를 출력한다. 모든 입력에 대하여 H는 10억 이하의 음이 아닌 정수이다.
풀이
도착지점부터 시작해서 top-down 방식으로 dp를 반복하며 풀었다.
사방탐색을 통해 이전 경로가 될 수 있는 위치를 찾으며, 그 위치의 값이 현재 값보다 큰 경우는 내리막길이기 때문에 경로에 더해준다.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static int M, N; // M=r, N=c
static int[][] map;
static int[][] dp;
static int[] dr = {1, -1, 0, 0};
static int[] dc = {0, 0, 1, -1};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
M = sc.nextInt();
N = sc.nextInt();
map = new int[M][N];
dp = new int[M][N];
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++) {
map[i][j] = sc.nextInt();
dp[i][j] = -1; // 초기화
}
dp[0][0] = 1; //처음 시작
find(M - 1, N - 1);
System.out.println(dp[M-1][N-1]);
}
static int find(int r, int c) {
if (dp[r][c]!=-1) return dp[r][c];
int ans =0;
for (int d=0; d<4; d++) {
int nr= r+dr[d];
int nc=c+dc[d];
if (nr>=0 && nr<M && nc>=0 && nc<N && map[nr][nc]>map[r][c]) {
ans += find(nr, nc);
}
}
return dp[r][c]=ans;
}
}
'문제 풀이 > BOJ' 카테고리의 다른 글
[백준] 17143 - 낚시왕 (자바 Java) (0) | 2022.10.26 |
---|---|
[백준] 12015 - 가장 긴 증가하는 부분 수열 2 (자바 Java) (0) | 2022.10.25 |
[백준] 11066 - 파일 합치기 (자바 Java) (0) | 2022.10.23 |
[백준] 7579 - 앱 (자바 Java) (0) | 2022.10.21 |
[백준] 17244 - 아맞다우산 (자바 Java) (0) | 2022.10.21 |