https://www.acmicpc.net/problem/2169
2169번: 로봇 조종하기
첫째 줄에 N, M(1≤N, M≤1,000)이 주어진다. 다음 N개의 줄에는 M개의 수로 배열이 주어진다. 배열의 각 수는 절댓값이 100을 넘지 않는 정수이다. 이 값은 그 지역의 가치를 나타낸다.
www.acmicpc.net
저는 DP를 통해 문제를 해결하였습니다.
DP를 통해 이전에 계산한 값을 다시 계산하지 않도록하여 시간안에 동작하도록 하였습니다.
package BOJ.dp;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.function.Function;
public class BOJ_2169_2 {
private static final int[] DY = {0,1,0};
private static final int[] DX = {-1,0,1};
private static final int DOWN = 1;
private static final int INF = 100 * 1_000 * 1_000;
private static final int NOT_VALID = 987654321;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine()," ");
Function<String,Integer> stoi = Integer::parseInt;
int n = stoi.apply(st.nextToken());
int m = stoi.apply(st.nextToken());
int[][] map = new int[n][m];
for(int i = 0 ; i < n ; i++){
st = new StringTokenizer(br.readLine()," ");
for(int j = 0 ; j < m ; j++){
map[i][j] = stoi.apply(st.nextToken());
}
}
int[][][] dp = new int[n][m][3];
for(int i = 0 ; i < n ; i++){
for(int j = 0 ; j < m ; j++){
Arrays.fill(dp[i][j],NOT_VALID);
}
}
int result = dfs(0,0,DOWN,map,n,m,dp);
System.out.println(result);
}
private static int dfs(int y , int x,int dir, int[][] map, int n, int m, int[][][] dp) {
if(y == n-1 && x == m-1){
return map[y][x];
}
if(dp[y][x][dir] != NOT_VALID){
return dp[y][x][dir];
}
int result = -INF;
for(int nextDir = 0 ; nextDir < 3 ; nextDir++){
if( (dir != DOWN) && (nextDir !=DOWN) && (dir != nextDir)){
continue;
}
int ny = y + DY[nextDir];
int nx = x + DX[nextDir];
if(!checkBound(ny,nx,n,m)){
continue;
}
result = Math.max(result,dfs(ny,nx,nextDir,map,n,m,dp));
}
dp[y][x][dir] = result + map[y][x];
return dp[y][x][dir];
}
private static boolean checkBound(int y ,int x , int n,int m){
if(y >= 0 && y < n && x >= 0 && x < m){
return true;
}
return false;
}
}
'알고리즘' 카테고리의 다른 글
백준 1890번 점프 (JAVA) (0) | 2023.12.30 |
---|---|
백준 1309번 동물원 (JAVA) (0) | 2023.12.29 |
백준 10773번 제로 (JAVA) (1) | 2023.12.27 |
백준 15810번 풍선 공장 (JAVA) (0) | 2023.12.26 |
백준 9465번 스티커 (JAVA) (1) | 2023.12.25 |