https://www.acmicpc.net/problem/1520
1520번: 내리막 길
여행을 떠난 세준이는 지도를 하나 구하였다. 이 지도는 아래 그림과 같이 직사각형 모양이며 여러 칸으로 나뉘어져 있다. 한 칸은 한 지점을 나타내는데 각 칸에는 그 지점의 높이가 쓰여 있으
www.acmicpc.net
조건
1. 지도의 숫자는 해당 칸의 높이
2. 시작 지점은 (0,0) 도착 지점은 (m, n)
3. 항상 내리막길만 이용 (이전 칸의 높이보다 낮은 칸으로만)
4. 상하좌우로만 이동
이 조건을 만족하는 경로의 개수를 모두 구하는 문제
"경로의 개수" 를 구해야 하기 때문에 dfs 를 사용
재귀를 통한 깊이 우선 탐색으로 조건에 나온 현재 지점보다 낮은 경로 탐색
public class Main {
static int m, n;
static int dm[] = {1, 0, -1, 0};
static int dn[] = {0, 1, 0, -1};
static int dp[][];
static int input[][];
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(reader.readLine());
m = Integer.parseInt(st.nextToken());
n = Integer.parseInt(st.nextToken());
input = new int[501][501];
dp = new int[501][501];
for(int i=0; i<m; i++){
st = new StringTokenizer(reader.readLine());
int idx = 0;
while(st.hasMoreTokens()){
input[i][idx] = Integer.parseInt(st.nextToken());
dp[i][idx++] = -1;
}
}
int result = dfs(0,0);
System.out.println(result);
}
public static int dfs(int x, int y){
if(x==m-1 || y==n-1){
return 1;
}
if(dp[x][y] != -1){
return dp[x][y];
}
dp[x][y]=0;
for(int i=0; i<4; i++){
int nextX = x+dm[i];
int nextY = y+dn[i];
if(nextX >= 0 && nextY >= 0 && nextX <m && nextY < n && input[nextX][nextY] < input[x][y]){
dp[x][y] += dfs(nextX, nextY);
}
}
return dp[x][y];
}
}
'코딩테스트 > 문제풀이' 카테고리의 다른 글
[프로그래머스] 상품을 구매한 회원 비율 구하기 SQL (0) | 2023.09.26 |
---|---|
[백준] 행렬 곱셈 순서 Java (0) | 2023.09.11 |
[백준] 퇴사 2 Java (0) | 2023.08.31 |
[백준] 2xn 타일링 Java (0) | 2023.08.30 |
[백준] 1, 2, 3 더하기 Java (0) | 2023.08.30 |