백준 2169 로봇 조종하기
유형
코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.Buffer;
import java.util.Arrays;
import java.util.StringTokenizer;
public class BOJ2169 {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer stz;
static int N, M;
static int weight[][];
static int dp[][];
static int INF = 1000000;
static int cache[][][];
static boolean visit[][];
static int dx[] = {0, 0, 1};
static int dy[] = {-1, 1, 0};
public static void main(String[] args) throws IOException {
stz = new StringTokenizer(br.readLine());
N = Integer.parseInt(stz.nextToken());
M = Integer.parseInt(stz.nextToken());
weight = new int[N+1][M+1];
dp = new int[N+1][M+1];
cache = new int[N+1][M+1][3];
visit = new boolean[N+1][M+1];
for(int i = 1; i <= N; i++) {
stz = new StringTokenizer(br.readLine());
for(int j = 1; j <= M; j++) {
weight[i][j] = Integer.parseInt(stz.nextToken());
cache[i][j][0] = cache[i][j][1] = cache[i][j][2] = -INF;
}
}
visit[1][1] = true;
System.out.println( dfs(1, 1, 0) );
}
public static void findMaxValue() {
dp[1][1] = weight[1][1];
for(int j = 2; j <= M; j++) {
dp[1][j] = dp[1][j-1] + weight[1][j];
}
int left[], right[];
for(int i = 2; i <= N; i++) {
left = new int[M+1];
left[0] = dp[i-1][1];
for(int j = 1 ; j <= M; j++) {
left[j] = Math.max(left[j-1], dp[i-1][j]) + weight[i][j];
}
right = new int[M+2];
right[M+1] = dp[i-1][M];
for(int j = M; j >=1 ; j--) {
right[j] = Math.max(right[j+1], dp[i-1][j]) + weight[i][j];
}
for(int j = 1; j <= M; j++) {
dp[i][j] = Math.max(left[j], right[j]);
}
}
System.out.println(dp[N][M]);
}
public static int dfs(int x, int y, int dir) {
if (x == N && y == M) return weight[x][y];
if (cache[x][y][dir] != -INF) return cache[x][y][dir];
for (int i = 0; i < 3; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
System.out.println(x + " " + y + " ");
System.out.println(nx + " " + ny + " ");
if (nx < 1 || nx > N || ny < 1 || ny > M || visit[nx][ny]) continue;
visit[nx][ny] = true;
cache[x][y][dir] = Math.max(cache[x][y][dir], dfs(nx, ny, i) + weight[x][y]);
visit[nx][ny] = false;
}
return cache[x][y][dir];
}
}