-
[KOITP] 내리막 길자료구조 및 알고리즘/문제풀이 2017. 1. 19. 07:40
출 처 : http://koitp.org/problem/SDS_PRO_7_2/read/
시간 제한 메모리 제한 제출 횟수 정답 횟수 (비율) 정답자 수 1.0 초 512 MB 1694 322 (19%) 273 < Comment >
문제 자체는 어렵지 않았습니다. 그러나 입력을 잘못 받는 탓에 계속 출력이 제대로 나오지 않아서 for 루프로 구현하던 것을 재귀 함수 호출식으로 변경하여 코드를 짜고도 조금 헤맸습니다. 전형적인 DP 문제이며, DP 함수를 i, j 위치에 도달하는 경로의 수 로 잡아두고 풀었습니다.
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.StringTokenizer; public class DecreasingRoad { public static long MOD = 1234567; public static long cache[][] = null; public static boolean isVisited[][] = null; public static int map[][] = null; public static int M = 0; public static int N = 0; public static int dx[] = {0, 0, 1, -1}; public static int dy[] = {1, -1, 0, 0}; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer st = new StringTokenizer(br.readLine()); M = Integer.parseInt(st.nextToken()); N = Integer.parseInt(st.nextToken()); map = new int[M + 1][N + 1]; cache = new long[M + 1][N + 1]; isVisited = new boolean[M + 1][N + 1]; cache[1][1] = 1; isVisited[1][1] = true; for (int i = 1 ; i <= M ; i++) { st = new StringTokenizer(br.readLine()); for (int j = 1 ; j <= N ; j++) { map[i][j] = Integer.parseInt(st.nextToken()); } } long result = dp(M, N); bw.write("" + result); bw.flush(); bw.close(); } public static long dp(int i, int j) { if (isVisited[i][j]) return cache[i][j]; isVisited[i][j] = true; long ret = 0; int nx = 0; int ny = 0; for (int k = 0 ; k < 4 ; k++) { nx = i + dx[k]; ny = j + dy[k]; if (nx < 1 || ny < 1 || nx > M || ny > N || map[nx][ny] <= map[i][j]) { continue; } ret = (ret + dp(nx, ny)) % MOD; } return cache[i][j] = ret; } }