-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0329_longest_increasing_path_in_a_matrix.html
More file actions
665 lines (572 loc) · 22.6 KB
/
Copy path0329_longest_increasing_path_in_a_matrix.html
File metadata and controls
665 lines (572 loc) · 22.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>329 - Longest Increasing Path in a Matrix</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#329</span> Longest Increasing Path in a Matrix</h1>
<p>
Given an m x n matrix of integers, return the length of the longest increasing path.
From each cell, you can move in 4 directions (up, down, left, right).
Uses DFS with memoization to cache path lengths.
</p>
<div class="problem-meta">
<span class="meta-tag">🔲 Matrix</span>
<span class="meta-tag">🧮 DP</span>
<span class="meta-tag">⏱️ O(m×n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0329_longest_increasing_path_in_a_matrix/0329_longest_increasing_path_in_a_matrix.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Tree traversal is like <strong>exploring a family tree</strong>:</p>
<ul>
<li><strong>Root:</strong> Start at the top node</li>
<li><strong>Recurse:</strong> Visit left and right children</li>
<li><strong>Base case:</strong> Stop at null/leaf nodes</li>
<li><strong>Combine:</strong> Build answer from subtree results</li>
</ul>
</div>
<section class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button id="autoRunBtn" class="btn">▶ Auto Run</button>
<button id="stepBtn" class="btn btn-success">Step</button>
<button id="resetBtn" class="btn btn-danger">Reset</button>
</div>
<div class="status" id="status">Click Auto Run to find the longest increasing path</div>
<svg id="visualization"></svg>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
from collections import deque
"""
LeetCode Longest Increasing Path In A Matrix
Problem from LeetCode: https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
Description:
Given an m x n integers matrix, return the length of the longest increasing path in matrix.
From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).
Example 1:
Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2:
Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
Example 3:
Input: matrix = [[1]]
Output: 1
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 200
0 <= matrix[i][j] <= 2^31 - 1
"""
class Solution:
def longest_increasing_path(self, matrix: List[List[int]]) ->int:
"""
Find the length of the longest increasing path in the matrix.
Args:
matrix: 2D array representing the matrix
Returns:
int: Length of the longest increasing path
"""
if not matrix or not matrix[0]:
return 0
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
m, n = len(matrix), len(matrix[0])
cache = [([0] * n) for _ in range(m)]
def dfs(i, j):
if cache[i][j] != 0:
return cache[i][j]
max_length = 1
for di, dj in dirs:
x, y = i + di, j + dj
if 0 <= x < m and 0 <= y < n and matrix[x][y] > matrix[i][j]:
max_length = max(max_length, 1 + dfs(x, y))
cache[i][j] = max_length
return max_length
ans = 0
for i in range(m):
for j in range(n):
ans = max(ans, dfs(i, j))
return ans
def longest_increasing_path_topological(self, matrix: List[List[int]]
) ->int:
"""
Find the length of the longest increasing path using topological sort.
Args:
matrix: 2D array representing the matrix
Returns:
int: Length of the longest increasing path
"""
if not matrix or not matrix[0]:
return 0
m, n = len(matrix), len(matrix[0])
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
in_degree = [([0] * n) for _ in range(m)]
for i in range(m):
for j in range(n):
for di, dj in dirs:
ni, nj = i + di, j + dj
if 0 <= ni < m and 0 <= nj < n and matrix[ni][nj] < matrix[
i][j]:
in_degree[i][j] += 1
queue = deque()
for i in range(m):
for j in range(n):
if in_degree[i][j] == 0:
queue.append((i, j))
path_length = 0
while queue:
path_length += 1
size = len(queue)
for _ in range(size):
i, j = queue.popleft()
for di, dj in dirs:
ni, nj = i + di, j + dj
if 0 <= ni < m and 0 <= nj < n and matrix[ni][nj] > matrix[
i][j]:
in_degree[ni][nj] -= 1
if in_degree[ni][nj] == 0:
queue.append((ni, nj))
return path_length
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
matrix1 = [
[9, 9, 4],
[6, 6, 8],
[2, 1, 1]
]
result1 = solution.longest_increasing_path(matrix1)
print(f"Example 1: {result1}") # Expected output: 4
# Example 2
matrix2 = [
[3, 4, 5],
[3, 2, 6],
[2, 2, 1]
]
result2 = solution.longest_increasing_path(matrix2)
print(f"Example 2: {result2}") # Expected output: 4
# Example 3
matrix3 = [[1]]
result3 = solution.longest_increasing_path(matrix3)
print(f"Example 3: {result3}") # Expected output: 1
# Using topological sort approach
print("\nUsing topological sort approach:")
result4 = solution.longest_increasing_path_topological(matrix1)
print(f"Example 1: {result4}") # Expected output: 4
</pre>
</div>
</section>
</div>
<script>
const width = 900;
const height = 600;
const svg = d3.select("#visualization")
.attr("width", width)
.attr("height", height);
// Sample matrix
const matrix = [
[9, 9, 4],
[6, 6, 8],
[2, 1, 1]
];
const rows = matrix.length;
const cols = matrix[0].length;
const cellSize = 70;
const offsetX = 80;
const offsetY = 80;
const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
const dirNames = ["→", "↓", "←", "↑"];
let cache = {};
let currentCell = null;
let exploringNeighbor = null;
let longestPath = [];
let currentPath = [];
let dfsStack = [];
let animationTimer = null;
let maxLength = 0;
function reset() {
cache = {};
currentCell = null;
exploringNeighbor = null;
longestPath = [];
currentPath = [];
dfsStack = [];
maxLength = 0;
if (animationTimer) clearInterval(animationTimer);
document.getElementById("status").textContent = "Click Auto Run to find the longest increasing path";
render();
}
function render() {
svg.selectAll("*").remove();
// Title
svg.append("text")
.attr("x", offsetX + (cols * cellSize) / 2)
.attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-size", "16px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Matrix");
// Draw grid
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const x = offsetX + c * cellSize;
const y = offsetY + r * cellSize;
const key = `${r},${c}`;
const isCurrent = currentCell && currentCell[0] === r && currentCell[1] === c;
const isNeighbor = exploringNeighbor && exploringNeighbor[0] === r && exploringNeighbor[1] === c;
const isInPath = currentPath.some(p => p[0] === r && p[1] === c);
const isInLongest = longestPath.some(p => p[0] === r && p[1] === c);
const isCached = cache[key] !== undefined;
svg.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", cellSize)
.attr("height", cellSize)
.attr("fill", () => {
if (isCurrent) return "#fef3c7";
if (isNeighbor) return "#e0e7ff";
if (isInLongest) return "#d1fae5";
if (isInPath) return "#dbeafe";
return "#f8fafc";
})
.attr("stroke", () => {
if (isCurrent) return "#f59e0b";
if (isInLongest) return "#10b981";
return "#94a3b8";
})
.attr("stroke-width", (isCurrent || isInLongest) ? 3 : 1);
// Value
svg.append("text")
.attr("x", x + cellSize / 2)
.attr("y", y + cellSize / 2)
.attr("text-anchor", "middle")
.attr("dominant-baseline", "middle")
.attr("font-size", "20px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(matrix[r][c]);
// Cache value
if (isCached) {
svg.append("text")
.attr("x", x + cellSize - 8)
.attr("y", y + 15)
.attr("text-anchor", "end")
.attr("font-size", "11px")
.attr("font-weight", "bold")
.attr("fill", "#10b981")
.text(cache[key]);
}
}
}
// Draw cache table
drawCache();
// Draw legend
drawLegend();
// Draw current path
if (currentPath.length > 1) {
drawPath(currentPath, "#3b82f6", "Current Path");
}
// Draw longest path
if (longestPath.length > 0) {
svg.append("text")
.attr("x", offsetX)
.attr("y", offsetY + rows * cellSize + 40)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#10b981")
.text(`Longest Path: ${longestPath.map(p => matrix[p[0]][p[1]]).join(" → ")} (length ${longestPath.length})`);
}
}
function drawPath(path, color, label) {
if (path.length < 2) return;
for (let i = 0; i < path.length - 1; i++) {
const x1 = offsetX + path[i][1] * cellSize + cellSize / 2;
const y1 = offsetY + path[i][0] * cellSize + cellSize / 2;
const x2 = offsetX + path[i + 1][1] * cellSize + cellSize / 2;
const y2 = offsetY + path[i + 1][0] * cellSize + cellSize / 2;
svg.append("line")
.attr("x1", x1)
.attr("y1", y1)
.attr("x2", x2)
.attr("y2", y2)
.attr("stroke", color)
.attr("stroke-width", 3)
.attr("stroke-dasharray", "5,3")
.attr("marker-end", "url(#arrow)");
}
// Arrow marker
svg.append("defs").append("marker")
.attr("id", "arrow")
.attr("viewBox", "0 0 10 10")
.attr("refX", 5)
.attr("refY", 5)
.attr("markerWidth", 4)
.attr("markerHeight", 4)
.attr("orient", "auto")
.append("path")
.attr("d", "M 0 0 L 10 5 L 0 10 z")
.attr("fill", color);
}
function drawCache() {
const cacheX = 400;
const cacheY = 80;
svg.append("text")
.attr("x", cacheX)
.attr("y", cacheY - 20)
.attr("font-size", "16px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Memoization Cache");
const entries = Object.entries(cache);
entries.forEach((entry, idx) => {
const row = Math.floor(idx / 3);
const col = idx % 3;
const x = cacheX + col * 140;
const y = cacheY + row * 35;
svg.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", 130)
.attr("height", 28)
.attr("rx", 4)
.attr("fill", "#ecfdf5")
.attr("stroke", "#10b981");
svg.append("text")
.attr("x", x + 65)
.attr("y", y + 18)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(`(${entry[0]}) → ${entry[1]}`);
});
}
function drawLegend() {
const legendX = 600;
const legendY = 350;
const items = [
{ color: "#fef3c7", label: "Current Cell", stroke: "#f59e0b" },
{ color: "#dbeafe", label: "In Current Path", stroke: "#3b82f6" },
{ color: "#d1fae5", label: "Longest Path", stroke: "#10b981" },
{ color: "#e0e7ff", label: "Exploring Neighbor", stroke: "#6366f1" }
];
svg.append("text")
.attr("x", legendX)
.attr("y", legendY - 20)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Legend");
items.forEach((item, i) => {
svg.append("rect")
.attr("x", legendX)
.attr("y", legendY + i * 30)
.attr("width", 20)
.attr("height", 20)
.attr("fill", item.color)
.attr("stroke", item.stroke)
.attr("stroke-width", 2);
svg.append("text")
.attr("x", legendX + 30)
.attr("y", legendY + i * 30 + 15)
.attr("font-size", "12px")
.attr("fill", "#1e293b")
.text(item.label);
});
}
function dfs(r, c, path = []) {
const key = `${r},${c}`;
if (cache[key] !== undefined) {
return cache[key];
}
let maxLen = 1;
const newPath = [...path, [r, c]];
for (const [dr, dc] of directions) {
const nr = r + dr;
const nc = c + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols
&& matrix[nr][nc] > matrix[r][c]) {
const len = 1 + dfs(nr, nc, newPath);
maxLen = Math.max(maxLen, len);
}
}
cache[key] = maxLen;
return maxLen;
}
function findLongestPath() {
cache = {};
maxLength = 0;
longestPath = [];
// Find max length first
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const len = dfs(r, c);
if (len > maxLength) {
maxLength = len;
}
}
}
// Reconstruct longest path
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (cache[`${r},${c}`] === maxLength) {
reconstructPath(r, c);
break;
}
}
if (longestPath.length > 0) break;
}
document.getElementById("status").textContent =
`Longest increasing path length: ${maxLength}`;
render();
}
function reconstructPath(r, c) {
longestPath.push([r, c]);
const key = `${r},${c}`;
const pathLen = cache[key];
if (pathLen === 1) return;
for (const [dr, dc] of directions) {
const nr = r + dr;
const nc = c + dc;
const nkey = `${nr},${nc}`;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols
&& matrix[nr][nc] > matrix[r][c]
&& cache[nkey] === pathLen - 1) {
reconstructPath(nr, nc);
return;
}
}
}
let stepQueue = [];
let stepIdx = 0;
function initSteps() {
stepQueue = [];
stepIdx = 0;
cache = {};
currentCell = null;
currentPath = [];
longestPath = [];
// Generate step sequence
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
generateSteps(r, c, []);
}
}
stepQueue.push({ type: "complete" });
}
function generateSteps(r, c, path) {
const key = `${r},${c}`;
stepQueue.push({ type: "visit", r, c, path: [...path] });
if (cache[key] !== undefined) {
stepQueue.push({ type: "cached", r, c, val: cache[key] });
return cache[key];
}
let maxLen = 1;
const newPath = [...path, [r, c]];
for (let i = 0; i < directions.length; i++) {
const [dr, dc] = directions[i];
const nr = r + dr;
const nc = c + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols
&& matrix[nr][nc] > matrix[r][c]) {
stepQueue.push({ type: "explore", nr, nc, from: [r, c], dir: dirNames[i] });
const len = 1 + generateSteps(nr, nc, newPath);
maxLen = Math.max(maxLen, len);
}
}
cache[key] = maxLen;
stepQueue.push({ type: "cache", r, c, val: maxLen });
return maxLen;
}
function step() {
if (stepQueue.length === 0) {
initSteps();
cache = {};
}
if (stepIdx >= stepQueue.length) {
findLongestPath();
return;
}
const s = stepQueue[stepIdx++];
switch (s.type) {
case "visit":
currentCell = [s.r, s.c];
currentPath = [...s.path, [s.r, s.c]];
exploringNeighbor = null;
document.getElementById("status").textContent =
`Visiting (${s.r},${s.c}) value=${matrix[s.r][s.c]}`;
break;
case "explore":
exploringNeighbor = [s.nr, s.nc];
document.getElementById("status").textContent =
`${s.dir} Exploring neighbor (${s.nr},${s.nc}) with value ${matrix[s.nr][s.nc]}`;
break;
case "cache":
cache[`${s.r},${s.c}`] = s.val;
document.getElementById("status").textContent =
`Caching: From (${s.r},${s.c}) longest path = ${s.val}`;
break;
case "cached":
document.getElementById("status").textContent =
`Using cached value for (${s.r},${s.c}): ${s.val}`;
break;
case "complete":
findLongestPath();
return;
}
render();
}
function autoRun() {
if (animationTimer) {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
if (stepQueue.length === 0 || stepIdx >= stepQueue.length) {
reset();
initSteps();
cache = {};
}
document.getElementById("autoRunBtn").textContent = "⏸ Pause";
animationTimer = setInterval(() => {
if (stepIdx >= stepQueue.length) {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
findLongestPath();
return;
}
step();
}, 300);
}
document.getElementById("autoRunBtn").addEventListener("click", autoRun);
document.getElementById("stepBtn").addEventListener("click", () => {
if (stepQueue.length === 0) {
initSteps();
cache = {};
}
step();
});
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>