본문 바로가기
자료구조 & 알고리즘/코딩 테스트

[백준 2812번 -dfs, dp] 내리막길(java)

by 코딩공장공장장 2023. 8. 23.

백준 1520번 - dfs, dp 

난이도 - 골드3

더보기
더보기
 

문제

여행을 떠난 세준이는 지도를 하나 구하였다. 이 지도는 아래 그림과 같이 직사각형 모양이며 여러 칸으로 나뉘어져 있다. 한 칸은 한 지점을 나타내는데 각 칸에는 그 지점의 높이가 쓰여 있으며, 각 지점 사이의 이동은 지도에서 상하좌우 이웃한 곳끼리만 가능하다.

 

현재 제일 왼쪽 위 칸이 나타내는 지점에 있는 세준이는 제일 오른쪽 아래 칸이 나타내는 지점으로 가려고 한다. 그런데 가능한 힘을 적게 들이고 싶어 항상 높이가 더 낮은 지점으로만 이동하여 목표 지점까지 가고자 한다. 위와 같은 지도에서는 다음과 같은 세 가지 경로가 가능하다.

  

지도가 주어질 때 이와 같이 제일 왼쪽 위 지점에서 출발하여 제일 오른쪽 아래 지점까지 항상 내리막길로만 이동하는 경로의 개수를 구하는 프로그램을 작성하시오.

 

입력

첫째 줄에는 지도의 세로의 크기 M과 가로의 크기 N이 빈칸을 사이에 두고 주어진다. 이어 다음 M개 줄에 걸쳐 한 줄에 N개씩 위에서부터 차례로 각 지점의 높이가 빈 칸을 사이에 두고 주어진다. M과 N은 각각 500이하의 자연수이고, 각 지점의 높이는 10000이하의 자연수이다.

 

출력

첫째 줄에 이동 가능한 경로의 수 H를 출력한다. 모든 입력에 대하여 H는 10억 이하의 음이 아닌 정수이다.

 

예제 입력 1

4 5
50 45 37 32 30
35 50 40 20 25
30 30 25 17 28
27 24 22 15 10

예제 출력 1

3
 

오답풀이 1: 

시간 복잡도 : O(mn^2)=(500x500)^2=625억

시간초과

import java.util.*;
import java.io.*;

public class Main{
    
    static int m;
    static int n;
    static int[][] arr;
    static int[][] pathArr;
    static int[][] sucArr;
    
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        m = Integer.parseInt(st.nextToken());
        n = Integer.parseInt(st.nextToken());
        arr = new int[m][n];
        pathArr = new int[m][n];
        sucArr = new int[m][n];
        for(int i=0; i<m; i++){
            st = new StringTokenizer(br.readLine());
            for(int j=0; j<n; j++) arr[i][j]= Integer.parseInt(st.nextToken());
        }
        
        dfs(0, 0);
        System.out.println(ans);
    }
    
    static int ans=0;
    public static void dfs(int strt, int end){
        if(strt==m-1 && end==n-1) {
        	ans++;
        	for(int i=0; i<m; i++) for(int j=0; j<n; j++) if(pathArr[i][j]==1) sucArr[i][j]=1;
        	return;
        }
        int curHeight=arr[strt][end];
        
        pathArr[strt][end]=1;
        if(strt>0 && pathArr[strt-1][end]!=1 && arr[strt-1][end]<curHeight) dfs(strt-1, end);
        if(end>0 && pathArr[strt][end-1]!=1 && arr[strt][end-1]<curHeight) dfs(strt, end-1);
        if(strt+1<m && pathArr[strt+1][end]!=1 && arr[strt+1][end]<curHeight) dfs(strt+1, end);
        if(end+1<n && pathArr[strt][end+1]!=1 && arr[strt][end+1]<curHeight) dfs(strt, end+1);
        pathArr[strt][end]=0;
    }
    
}

 

오답풀이 2: 

import java.util.*;
import java.io.*;

public class Main{
    
    static int m;
    static int n;
    static int[][] arr;
    static int[][] pathArr;
    static int[][] sucArr;
    
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        m = Integer.parseInt(st.nextToken());
        n = Integer.parseInt(st.nextToken());
        arr = new int[m][n];
        pathArr = new int[m][n];
        sucArr = new int[m][n];
        for(int i=0; i<m; i++){
            st = new StringTokenizer(br.readLine());
            for(int j=0; j<n; j++) arr[i][j]= Integer.parseInt(st.nextToken());
        }
        
        dfs(0, 0);
        System.out.println(ans);
    }
    
    
    public static void record() {
    	ans++;
    	for(int i=0; i<m; i++) for(int j=0; j<n; j++) if(pathArr[i][j]==1) sucArr[i][j]=1;
    }
    
    static int ans=0;
    public static void dfs(int strt, int end){
        if(strt==m-1 && end==n-1) {
        	record();
        	return;
        }
        int curHeight=arr[strt][end];
        
        pathArr[strt][end]=1;
        if(strt>0 && pathArr[strt-1][end]!=1 && arr[strt-1][end]<curHeight) {
        	if(sucArr[strt-1][end]==1) record();
        	else dfs(strt-1, end);
        }
        if(end>0 && pathArr[strt][end-1]!=1 && arr[strt][end-1]<curHeight) {
        	if(sucArr[strt][end-1]==1) record();
        	else dfs(strt, end-1);
        }
        if(strt+1<m && pathArr[strt+1][end]!=1 && arr[strt+1][end]<curHeight) {
        	if(sucArr[strt+1][end]==1) record();
        	else dfs(strt+1, end);
        }
        if(end+1<n && pathArr[strt][end+1]!=1 && arr[strt][end+1]<curHeight) {
        	if(sucArr[strt][end+1]==1) record();
        	else dfs(strt, end+1);
        }
        pathArr[strt][end]=0;
    }
    
}

 

정답풀이 : 

dfs + dp로 연산 줄임

import java.util.*;
import java.io.*;

public class Main{
    
    static int m, n;
    static int[][] arr, dp;
    static int[] rangeX = {-1, 0, 1, 0};
    static int[] rangeY = {0, -1, 0, 1};
    
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        m=Integer.valueOf(String.valueOf(st.nextToken()));
        n=Integer.valueOf(String.valueOf(st.nextToken()));
        arr = new int[m][n];
        dp = new int[m][n];
        for(int i=0; i<m; i++){
            st = new StringTokenizer(br.readLine());
            for(int j=0; j<n; j++) arr[i][j]=Integer.valueOf(String.valueOf(st.nextToken()));
        }
        
        for(int i=0; i<m; i++) for(int j=0; j<n; j++) dp[i][j]=-1;
        
        System.out.println(dfs(0,0));
    }
    
    
    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 dx=x+rangeX[i];
            int dy=y+rangeY[i];
            if(dx<0 || dy<0 || dx==m || dy==n) continue;
            
            if(arr[x][y]>arr[dx][dy]) dp[x][y] += dfs(dx, dy);
        }
        return dp[x][y];
    }
    
}

 

반응형