상세 컨텐츠

본문 제목

[백준] 내리막길 - 애매함

💯ProblemSolving/문제 풀이-Java

by :부셔져버린개발자 2025. 2. 5. 09:44

본문

       문제 요약        

- 문제

https://www.acmicpc.net/problem/1520

 

 

         아이디어        

 

dfs + 메모이제이션 

이미 방문한 적이 있다면 지금까지 경로 수 리턴 

 

         소스코드        

 

 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
	static int M, N; // 세로의 크기, 가로의 크기
	static int[][] box;
	static int[][] way = { { -1, 0 }, { 1, 0 }, { 0, 1 }, { 0, -1 } };
	static int[][] dp;

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		M = Integer.parseInt(st.nextToken());
		N = Integer.parseInt(st.nextToken());
		box = new int[M][N];
		dp = new int[M + 1][N + 1];
		for (int m = 0; m < M; m++) {
			st = new StringTokenizer(br.readLine());
			for (int n = 0; n < N; n++) {
				box[m][n] = Integer.parseInt(st.nextToken());
				dp[m][n] = -1;
			}
		}

		System.out.println(dfs(0, 0));

	}

	private static int dfs(int i, int j) {
		if (i == M - 1 && j == N - 1) {
			return 1; // M-1, N-1까지 오는 방법의 수 +1
		}
		if (dp[i][j] != -1) { // 이미 방문한 적이 있음
			return dp[i][j];
		}
		dp[i][j] = 0; // 방문처리
		for (int w = 0; w < 4; w++) {
			int nx = i + way[w][0];
			int ny = j + way[w][1];
			if (nx < 0 || nx >= M || ny < 0 || ny >= N) {
				continue;
			}
			if (box[i][j] > box[nx][ny]) {
				dp[i][j] += dfs(nx, ny); // ...!
			}
		}
		return dp[i][j];
	}

	static boolean inRange(int x, int y) {
		return x >= 0 && x < M && y >= 0 && y < N;
	}

}

 

728x90

관련글 더보기