public static int getRecursiveCost(int i, int j) {
// Boundary case.
if ( i == 0 && j == 0 ) {
return rooms[i][j];
}
// Reach bottom
if ( i == 0 ) {
return rooms[i][j] + getRecursiveCost(i,j-1);
}
// Reach leftest.
if ( j == 0 ) {
return rooms[i][j] + getRecursiveCost(i-1,j);
}
int right = getRecursiveCost(i-1,j);
int down = getRecursiveCost(i,j-1);
if ( right > down ) {
return rooms[i][j] + right;
}
return rooms[i][j] + down;
}
public static int getMemoizedCost(int i, int j) {
if ( costs[i][j] != 0 ) {
return costs[i][j];
}
// Boundary case.
if ( i == 0 && j == 0 ) {
costs[i][j] = rooms[i][j];
return costs[i][j];
}
// Reach bottom
if ( i == 0 ) {
costs[i][j] = rooms[i][j] + getMemoizedCost(i,j-1);
return costs[i][j];
}
// Reach leftest.
if ( j == 0 ) {
costs[i][j] = rooms[i][j] + getMemoizedCost(i-1,j);
return costs[i][j];
}
int right = getMemoizedCost(i-1,j);
int down = getMemoizedCost(i,j-1);
if ( right > down ) {
costs[i][j] = rooms[i][j] + right;
return costs[i][j];
}
costs[i][j] = rooms[i][j] + down;
return costs[i][j];
}
public static void main(String[] args) {
// Read input data
read();
// Compute
for ( int i=0 ; i < 5 ; i++ ) {
for ( int j=0 ; j < 6 ; j++ ) {
//costs[i][j] = getMemoizedCost(i,j);
if ( i == 0 && j == 0 ) {
rooms[i][j] = rooms[i][j];
} else if ( i == 0 ) {
rooms[i][j] = rooms[i][j] + rooms[i][j-1];
} else if ( j == 0 ) {
rooms[i][j] = rooms[i][j] + rooms[i-1][j];
} else {
if ( rooms[i-1][j] > rooms[i][j-1] ) {
rooms[i][j] = rooms[i][j] + rooms[i-1][j];
} else {
rooms[i][j] = rooms[i][j] + rooms[i][j-1];
}
}
}
}
printMatrix(rooms);
}
이전 글 : ASP.NET 가이드 4. 통합 예외처리
다음 글 : PWM에 대하여
최신 콘텐츠