news 2026/10/13 7:03:02

元宝 LeetCode 329. Longest Increasing Path in a Matrix Java Implement

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
元宝 LeetCode 329. Longest Increasing Path in a Matrix Java Implement

Core idea: DFS + memoization. The grid is a DAG — every edge goes from a smaller value to a larger one, so no cycles and no need for a
“visited” set.
“dfs(r,c)” = longest increasing path starting at
“(r,c)”, computed once per cell and cached.

class Solution {
private static final int[][] DIRS = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
private int rows, cols;
private int[][] memo;
private int[][] grid;

public int longestIncreasingPath(int[][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0; rows = matrix.length; cols = matrix[0].length; grid = matrix; memo = new int[rows][cols]; // 0 = not computed yet int ans = 0; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { ans = Math.max(ans, dfs(r, c)); } } return ans; } /** Longest increasing path starting at (r, c). */ private int dfs(int r, int c) { if (memo[r][c] != 0) return memo[r][c]; int best = 1; for (int[] d : DIRS) { int nr = r + d[0], nc = c + d[1]; if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue; if (grid[nr][nc] <= grid[r][c]) continue; // must strictly increase best = Math.max(best, 1 + dfs(nr, nc)); } return memo[r][c] = best; }

}

Key points

  • No
    “visited” needed: strict increase guarantees a DAG, so recursion can never loop back.
  • Move to a neighbor only if strictly greater — equal values must be rejected (
    “<=”, not
    “<”).

“memo” defaults to
“0” as “uncomputed” because every real answer is
“≥ 1”.

  • 1-D encoding
    “r * cols + c” works too if you prefer flat arrays.

Complexity: each cell’s DFS body runs once →
“O(m·n)” time,
“O(m·n)” space for the memo.

One caveat: recursion depth equals the path length, which can reach
“m·n = 40,000” on a 200×200 monotone grid. I reproduced a
“StackOverflowError” at default stack size on such a case. If you want a stack-safe variant, peel the DAG by layers with Kahn’s algorithm — start from all local minima (out-degree 0 in the “increasing” direction), strip one BFS layer at a time, and the number of layers is the answer:

// edges point from smaller -> larger; out[id] = count of strictly greater neighbors
for (int r = 0; r < R; r++) for (int c = 0; c < C; c++)
for (int[] d : D) { /* neighbor in bounds && grid[nr][nc] > grid[r][c] -> out[r*C+c]++ */ }

ArrayDeque q = new ArrayDeque<>();
for (int i = 0; i < N; i++) if (out[i] == 0) q.add(i); // local maxima as seeds

int level = 0;
while (!q.isEmpty()) {
for (int s = q.size(); s > 0; s–) {
int id = q.poll(), r = id / C, c = id % C;
for (int[] d : D) { // walk edges backwards
/* neighbor in bounds && grid[pr][pc] < grid[r][c] -> if (–out[pid] == 0) q.add(pid) */
}
}
level++;
}
return level; // same O(m·n) time, no recursion

Verified: 3,000 random grids (with deliberate ties) against a brute-force DP, plus all official samples (
“4” /
“4” /
“1”), and the Kahn version returns
“40000” on the snake grid where DFS overflows.

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/10/13 7:02:56

AI 数学基础知识

范围&#xff1a;AI 学习阶段 A 的数学三条主线——“矩阵线性变换、梯度方向导数、交叉熵信息论”——的知识点展开。面向 20 年工程经验读者&#xff1a;不啃证明&#xff0c;每个知识点只回答两个问题——它在深度学习里对应什么 / 后面哪个实验会用到。结论先行 AI 所需的数…

作者头像 李华
网站建设 2026/10/13 7:02:55

Redis 从入门到实战(12):性能调优与生产避坑(完结)

性能调优与生产避坑 本篇命令全部实测(Redis 7.4.11)。收官篇:把前面 11 篇的知识变成线上战斗力。 一、性能排查的三板斧 遇到 Redis 慢,按这个顺序排查: #mermaid-svg-c3qvFd5v0vxNscNd{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px…

作者头像 李华
网站建设 2026/10/13 7:02:06

幻 觉

很多新概念都是换汤不换药&#xff0c;工作的本质上并没有什么改变。AI的差距在于卡和数据&#xff0c;人的差距大概是方法论。 下面这一套东西api&#xff0c;打通了完全可以agent化。 用一个前辈中肯的话说&#xff0c;现在AI方向的一些工作&#xff0c;大部分人跟时间是在处…

作者头像 李华
网站建设 2026/10/13 7:01:49

项目管理到底是在管人还是管事?具体项目进程中引发的思考

1. 引言周五下午&#xff0c;项目例会开到一半&#xff0c;会议室里的气氛却越来越僵。开发组长老张拍着桌子说&#xff1a;「我早就说过&#xff0c;这个需求根本排不进这轮迭代&#xff0c;你们只盯着进度表&#xff0c;谁管过我们组已经连续加班三周了&#xff1f;」坐在对面…

作者头像 李华
网站建设 2026/10/13 7:01:48

Allegro 动态铜皮不更新与焊盘不连接问题排查记录

Allegro 动态铜皮不更新与焊盘不连接问题排查记录Allegro 动态铜皮不更新与焊盘不连接问题排查记录一、问题起因1. 动态铜皮大面积过期2. GND 焊盘无法连接铜皮二、排查过程问题 1&#xff1a;铜皮无法更新&#xff08;Out of date&#xff09;第一步&#xff1a;排除数据库损坏…

作者头像 李华
网站建设 2026/10/13 7:01:21

学术文献检索式构建技巧与实战指南

1. 文献检索式基础概念解析文献检索式是学术研究中获取目标文献的核心工具&#xff0c;相当于给数据库的精准指令。就像使用搜索引擎时输入关键词组合一样&#xff0c;但学术数据库的检索语法更为严谨和专业。一个合格的检索式需要同时满足查全率&#xff08;recall&#xff09…

作者头像 李华