publicintlongestIncreasingPath(int[][] matrix) { intm= matrix.length, n = matrix[0].length; // Get all nodes inDegree count int[][] inDegree = newint[m][n]; for (inti=0; i < m; i++) { for (intj=0; j < n; j++) { for (int[] direction : DIRECTIONS) { intnewRow= i + direction[0]; intnewCol= j + direction[1]; if (!isOutOfBound(m, n, newRow, newCol) && matrix[i][j] < matrix[newRow][newCol]) { inDegree[newRow][newCol] += 1; } } } }
// Get all nodes with no inDegree edges Deque<int[]> noDegreeNodes = newArrayDeque<>(); for (inti=0; i < m; i++) { for (intj=0; j < n; j++) { if (inDegree[i][j] == 0) { noDegreeNodes.offer(newint[] { i, j }); } } }
// Topological Sort intlength=0; while (!noDegreeNodes.isEmpty()) { intsize= noDegreeNodes.size(); for (inti=0; i < size; i++) { int[] currPos = noDegreeNodes.poll(); for (int[] direction : DIRECTIONS) { intnewRow= currPos[0] + direction[0]; intnewCol= currPos[1] + direction[1]; if (!isOutOfBound(m, n, newRow, newCol) && matrix[currPos[0]][currPos[1]] < matrix[newRow][newCol]) { inDegree[newRow][newCol] -= 1; if (inDegree[newRow][newCol] == 0) { noDegreeNodes.offer(newint[] { newRow, newCol }); } } } } length += 1; } return length;
}
privatebooleanisOutOfBound(int rowLength, int colLength, int row, int col) { return row < 0 || row >= rowLength || col < 0 || col >= colLength; } }