3459 - Length of Longest V-Shaped Diagonal Segment
정보
- 문제 보기: 3459 - Length of Longest V-Shaped Diagonal Segment
- 소요 시간: 47분 29초
- 풀이 언어:
java
- 체감 난이도: 3️⃣~4️⃣ (3.7)
- 리뷰 횟수: ✅
풀이 키워드
스포주의
DP
풀이 코드
정보
- 메모리: 143900 KB
- 시간: 424 ms
class Solution {
int[] dy = {-1, -1, 1, 1}; // lu, ru, rd, ld
int[] dx = {-1, 1, 1, -1};
int[][] grid;
int n, m;
int[][][][] memo;
int dp(int y, int x, int dir, int turned) {
//System.out.println("dp(" + y + ", " + x + ", " + dir + ", " + turned + ")");
if ((y == 0 || y == n-1 || x == 0 || x == m-1) && turned == 1) return 1;
if (memo[y][x][dir][turned] != 0) return memo[y][x][dir][turned];
int res = 0;
int curVal = grid[y][x];
// no turn
{
int ny = y + dy[dir];
int nx = x + dx[dir];
// bound check
if (0 <= ny && ny <= n-1 && 0 <= nx && nx <= m-1) {
int nxtVal = grid[ny][nx];
// value check
if (nxtVal != 1 && nxtVal != curVal)
res = Math.max(res, dp(ny, nx, dir, turned));
}
}
// turn
if (turned == 0) {
int nTurned = 1; // true
int ndir = (dir + 1) % 4;
int ny = y + dy[ndir];
int nx = x + dx[ndir];
// bound check
if (0 <= ny && ny <= n-1 && 0 <= nx && nx <= m-1) {
int nxtVal = grid[ny][nx];
// value check
if (nxtVal != 1 && nxtVal != curVal)
res = Math.max(res, dp(ny, nx, ndir, nTurned));
}
}
//System.out.println("dp(" + y + ", " + x + ", " + dir + ", " + turned + ") = " + (res+1));
return memo[y][x][dir][turned] = res + 1;
}
public int lenOfVDiagonal(int[][] grid) {
this.grid = grid;
n = grid.length;
m = grid[0].length;
memo = new int[n][m][4][2];
int mx = 0;
int self = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (grid[i][j] != 1) continue;
self = 1; // 1 exists
for (int d = 0; d < 4; ++d) { // 4 directions
int ny = i + dy[d];
int nx = j + dx[d];
// bound check
if (0 <= ny && ny <= n-1 && 0 <= nx && nx <= m-1) {
// if matches the first number of the seq
if (grid[ny][nx] == 2)
mx = Math.max(mx, dp(ny, nx, d, 0));
}
}
}
}
return mx == 0 ? self : mx+1;
}
}
풀이 해설
첫 칸은 1, 이후부턴 2, 0, 2, 0, ... 식으로 이어지며
진행방향은 대각선만 가능하고, 최대 딱 1번 시계방향 90도로 진행방향을 꺾을 수 있을 때
가장 길게 뽑을 수 있는 경로의 길이를 구하는 고차원 DP 문제이다.