LeetCode 329 矩阵中最长增长路径
取自官方题解
class Solution {
//方向矩阵: 上、下、左、右
public int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public int rows, columns;
public int longestIncreasingPath(int[][] matrix) {
//边界条件
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
rows = matrix.length;
columns = matrix[0].length;
//记忆数组
int[][] memo = new int[rows][columns];
int ans = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns; ++j) {
ans = Math.max(ans, dfs(matrix, i, j, memo));
}
}
return ans;
}
//递归求解子问题
public int dfs(int[][] matrix, int row, int column, int[][] memo) {
//取子问题解: 由(row, column)点出发的最长递增路径
if (memo[row][column] != 0) {
return memo[row][column];
}
//memo[row][column]至少为1,此时该路径下只有点(row, column)
++memo[row][column];
//由点(row, column)向四个方向上搜索
for (int[] dir : dirs) {
int newRow = row + dir[0], newColumn = column + dir[1];
if (//边界控制
newRow >= 0 &&
newRow < rows &&
newColumn >= 0 &&
newColumn < columns &&
//满足路径增长条件(增加)
matrix[newRow][newColumn] > matrix[row][column]) {
//求解子问题: (row, column)出发的最长递增路径,并存储
memo[row][column] = Math.max(memo[row][column], dfs(matrix, newRow, newColumn, memo) + 1);
}
}
return memo[row][column];
}
}
class Solution {
public int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public int rows, columns;
public int longestIncreasingPath(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
rows = matrix.length;
columns = matrix[0].length;
//出度矩阵(小值点->大值点),用于存储生成的有向图中每个节点的出度数量
int[][] outdegrees = new int[rows][columns];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns; ++j) {
for (int[] dir : dirs) {
int newRow = i + dir[0], newColumn = j + dir[1];
if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns &&
matrix[newRow][newColumn] > matrix[i][j]) {
++outdegrees[i][j];
}
}
}
}
Queue<int[]> queue = new LinkedList<int[]>();
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns; ++j) {
//寻找图中所有无出度的节点(每条增长路径的终点)
if (outdegrees[i][j] == 0) {
queue.offer(new int[]{i, j});
}
}
}
int ans = 0;
while (!queue.isEmpty()) {
++ans;
int size = queue.size();
//遍历并删除当前图中每个无出度节点,该过程中同时添加新产生的无出度节点
for (int i = 0; i < size; ++i) {
int[] point = queue.poll();
int row = point[0], column = point[1];
for (int[] dir : dirs) {
int newRow = row + dir[0], newColumn = column + dir[1];
if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns &&
matrix[newRow][newColumn] < matrix[row][column]) {
--outdegrees[newRow][newColumn];
if (outdegrees[newRow][newColumn] == 0) {
queue.offer(new int[]{newRow, newColumn});
}
}
}
}
}
return ans;
}
}