public int longestIncreasingPath(int[][] matrix) {
int m = matrix.length; n = matrix[0].length;
int[][] indegree = new int[m][n];
Queue<int[]> q = new LinkedList();
for (int row = 0; row < m; row++) {
for (int col = 0; col < n; col++) {
for(int i = 0; i < 4; i++) {
int nextRow = row + dirs[i][0];
int nextCol = col + dirs[i][1];
if (nextRow >= 0 && nextRow < m && nextCol >= 0 && nextCol < n &&
matrix[row][col] > matrix[nextRow][nextCol]) {
indegree[row][col]++;
}
}
if (indegree[row][col] == 0) q.offer(new int[]{row, col});
}
}
int len = 0;
while (!q.isEmpty()) {
int size = q.size();
while (size-- > 0) { // consume all nodes in cur layer and add next layer into queue
int[] coord = q.poll();
int row = coord[0], col = coord[1];
for(int i = 0; i < 4; i++) {
int nextRow = row + dirs[i][0];
int nextCol = col + dirs[i][1];
if (nextRow >= 0 && nextRow < m && nextCol >= 0 && nextCol < n &&
matrix[row][col] < matrix[nextRow][nextCol]) {
if (--indegree[nextRow][nextCol] == 0) // remove edge
q.offer(new int[]{nextRow, nextCol}); // add as next level node
}
}
}
len++; // at the end of each layer, increase the length
}
return len;
}