Please describe the bug below and include any steps to reproduce the bug or screenshots if possible.
My solution is exactly the same as the editor solution, but mine fails while the editor solution works. The irony is that mine works on LeetCode too — all the approaches. There is something wrong with the compiler or the stack size limit. It throws NZEC for mine but not for the editor solution. The only difference I can see is a variable with a different name (passing memo as a parameter vs. using a class field).
class Solution {
int[][] dir = new int[][]{{0,1},{0,-1},{1,0},{-1,0}};
int[][] memo;
public int longestIncreasingPath(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int maxi = 0;
memo = new int[matrix.length][matrix[0].length];
for (int[] mm : memo) {
Arrays.fill(mm, -1);
}
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
maxi = Math.max(maxi, dfs(matrix, row, col, Integer.MIN_VALUE));
}
}
return maxi;
}
private int dfs(int[][] matrix, int i, int j, int prevVal) {
if (!isValid(matrix, i, j) || prevVal >= matrix[i][j]) {
return 0;
}
if (memo[i][j] != -1) {
return memo[i][j];
}
int cnt = 1;
for (int idx = 0; idx < 4; idx++) {
int nr = i + dir[idx][0];
int nc = j + dir[idx][1];
cnt = Math.max(cnt, 1 + dfs(matrix, nr, nc, matrix[i][j]));
}
memo[i][j] = cnt;
return cnt;
}
private boolean isValid(int[][] matrix, int i, int j) {
return i >= 0 && j >= 0 && i < matrix.length && j < matrix[0].length;
}
}
Bug Report for https://neetcode.io/problems/longest-increasing-path-in-matrix
Please describe the bug below and include any steps to reproduce the bug or screenshots if possible.
My solution is exactly the same as the editor solution, but mine fails while the editor solution works. The irony is that mine works on LeetCode too — all the approaches. There is something wrong with the compiler or the stack size limit. It throws NZEC for mine but not for the editor solution. The only difference I can see is a variable with a different name (passing memo as a parameter vs. using a class field).
Editor Solution: link
Editorial: link
Mine Solution: link