-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0062_unique_paths.html
More file actions
534 lines (458 loc) · 19.7 KB
/
0062_unique_paths.html
File metadata and controls
534 lines (458 loc) · 19.7 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>62 - Unique Paths</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">#62</span> Unique Paths</h1>
<p>
A robot on an m×n grid can only move right or down. Count the number of
unique paths from top-left to bottom-right corner.
</p>
<div class="problem-meta">
<span class="meta-tag">🧮 DP</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0062_unique_paths/0062_unique_paths.py</code>
</div>
<h3>Example:</h3>
<pre>
m = 3, n = 7
Output: 28 unique paths
</pre>
</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="stepBtn" class="btn">Step</button>
<button id="autoBtn" class="btn btn-success">Auto Run</button>
<button id="resetBtn" class="btn btn-danger">Reset</button>
</div>
<div class="status" id="status">Count paths: robot can only move right or down</div>
<svg id="visualization"></svg>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Unique Paths
Problem from LeetCode: https://leetcode.com/problems/unique-paths/
Description:
There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m-1][n-1]). The robot can only move either down or right at any point in time.
Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.
Example 1:
Input: m = 3, n = 7
Output: 28
Example 2:
Input: m = 3, n = 2
Output: 3
Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
"""
class Solution:
def unique_paths(self, m: int, n: int) -> int:
"""
Calculate the number of unique paths from top-left to bottom-right.
Uses dynamic programming with O(m*n) time and space complexity.
Args:
m: Number of rows in the grid
n: Number of columns in the grid
Returns:
int: Number of unique paths
"""
# Initialize dp table with 1s for the first row and column
dp = [[1] * n for _ in range(m)]
# Fill the dp table
for i in range(1, m):
for j in range(1, n):
# Number of ways to reach (i,j) = ways to reach from above + ways to reach from left
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[m-1][n-1]
def unique_paths_optimized(self, m: int, n: int) -> int:
"""
Calculate unique paths with optimized space complexity O(n).
Args:
m: Number of rows
n: Number of columns
Returns:
int: Number of unique paths
"""
# Use a single row of the dp table
dp = [1] * n
# Update the dp array m-1 times
for i in range(1, m):
for j in range(1, n):
# dp[j] now represents the number of ways to reach cell (i,j)
dp[j] += dp[j-1]
return dp[n-1]
def unique_paths_math(self, m: int, n: int) -> int:
"""
Calculate unique paths using mathematical combination formula.
The problem is equivalent to choosing which steps to go down (or right).
Args:
m: Number of rows
n: Number of columns
Returns:
int: Number of unique paths
"""
# Total steps needed: (m-1) down steps + (n-1) right steps = (m+n-2) total steps
# We need to choose which of these steps are down (or right)
# This is equivalent to choosing (m-1) positions from (m+n-2) positions
# The formula is C(m+n-2, m-1) = (m+n-2)! / ((m-1)! * (n-1)!)
import math
return math.comb(m + n - 2, m - 1)
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
m1, n1 = 3, 7
result1 = solution.unique_paths(m1, n1)
print(f"Example 1: m={m1}, n={n1}, paths={result1}") # Expected output: 28
# Example 2
m2, n2 = 3, 2
result2 = solution.unique_paths(m2, n2)
print(f"Example 2: m={m2}, n={n2}, paths={result2}") # Expected output: 3
# Additional example
m3, n3 = 10, 10
result3 = solution.unique_paths(m3, n3)
print(f"Example 3: m={m3}, n={n3}, paths={result3}") # Expected output: 48620
# Compare different implementations
print("\nComparing implementations:")
print(f"Standard DP: {solution.unique_paths(m1, n1)}")
print(f"Optimized space: {solution.unique_paths_optimized(m1, n1)}")
print(f"Math formula: {solution.unique_paths_math(m1, n1)}")
</pre>
</div>
</section>
</div>
<script>
const width = 900;
const height = 550;
const svg = d3.select("#visualization")
.attr("width", width)
.attr("height", height);
const m = 4;
const n = 5;
const cellSize = 70;
let dp = [];
let currentI = 0;
let currentJ = 0;
let isRunning = false;
let phase = "init";
let samplePath = [];
function reset() {
dp = Array.from({ length: m }, () => Array(n).fill(0));
currentI = 0;
currentJ = 0;
phase = "init";
samplePath = [];
isRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
document.getElementById("status").textContent =
`Grid: ${m}×${n}. Robot moves right or down only.`;
render();
}
function render() {
svg.selectAll("*").remove();
const startX = 80;
const startY = 60;
// Title
svg.append("text")
.attr("x", startX + (n * cellSize) / 2)
.attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-size", "16px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(`${m} × ${n} Grid`);
// Grid cells
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
const x = startX + j * cellSize;
const y = startY + i * cellSize;
const isActive = i === currentI && j === currentJ && phase === "fill";
const isStart = i === 0 && j === 0;
const isEnd = i === m - 1 && j === n - 1;
const isFilled = phase === "init" ? false :
phase === "base" ? (i === 0 || j === 0) :
(i < currentI || (i === currentI && j <= currentJ)) || phase === "done";
// Cell rectangle
svg.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", cellSize - 2)
.attr("height", cellSize - 2)
.attr("rx", 6)
.attr("fill", () => {
if (isStart) return "#dbeafe";
if (isEnd && phase === "done") return "#d1fae5";
if (isActive) return "#fef3c7";
if (isFilled) return "#f8fafc";
return "#f1f5f9";
})
.attr("stroke", () => {
if (isStart) return "#3b82f6";
if (isEnd) return "#10b981";
if (isActive) return "#f59e0b";
return "#e2e8f0";
})
.attr("stroke-width", (isStart || isEnd || isActive) ? 2 : 1);
// Path count
if (isFilled || isStart) {
svg.append("text")
.attr("x", x + (cellSize - 2) / 2)
.attr("y", y + (cellSize - 2) / 2 + 6)
.attr("text-anchor", "middle")
.attr("font-size", "20px")
.attr("font-weight", "bold")
.attr("fill", isEnd ? "#10b981" : "#1e293b")
.text(dp[i][j] || 1);
}
// Start/End labels
if (isStart) {
svg.append("text")
.attr("x", x + (cellSize - 2) / 2)
.attr("y", y - 8)
.attr("text-anchor", "middle")
.attr("font-size", "11px")
.attr("fill", "#3b82f6")
.text("START");
}
if (isEnd) {
svg.append("text")
.attr("x", x + (cellSize - 2) / 2)
.attr("y", y - 8)
.attr("text-anchor", "middle")
.attr("font-size", "11px")
.attr("fill", "#10b981")
.text("END");
}
}
}
// Draw arrows showing source cells
if (phase === "fill" && currentI > 0 && currentJ > 0) {
const x = startX + currentJ * cellSize;
const y = startY + currentI * cellSize;
const cx = x + (cellSize - 2) / 2;
const cy = y + (cellSize - 2) / 2;
// Arrow from top
svg.append("line")
.attr("x1", cx)
.attr("y1", y - 15)
.attr("x2", cx)
.attr("y2", y + 5)
.attr("stroke", "#3b82f6")
.attr("stroke-width", 2)
.attr("marker-end", "url(#arrowBlue)");
// Arrow from left
svg.append("line")
.attr("x1", x - 15)
.attr("y1", cy)
.attr("x2", x + 5)
.attr("y2", cy)
.attr("stroke", "#a855f7")
.attr("stroke-width", 2)
.attr("marker-end", "url(#arrowPurple)");
}
// Arrow markers
const defs = svg.append("defs");
defs.append("marker")
.attr("id", "arrowBlue")
.attr("viewBox", "0 -5 10 10")
.attr("refX", 8)
.attr("refY", 0)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("path")
.attr("d", "M0,-5L10,0L0,5")
.attr("fill", "#3b82f6");
defs.append("marker")
.attr("id", "arrowPurple")
.attr("viewBox", "0 -5 10 10")
.attr("refX", 8)
.attr("refY", 0)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("path")
.attr("d", "M0,-5L10,0L0,5")
.attr("fill", "#a855f7");
// Robot
const robotX = startX + (phase === "done" ? (n - 1) : 0) * cellSize + (cellSize - 2) / 2;
const robotY = startY + (phase === "done" ? (m - 1) : 0) * cellSize + (cellSize - 2) / 2;
svg.append("circle")
.attr("cx", robotX)
.attr("cy", robotY)
.attr("r", 12)
.attr("fill", "#f59e0b")
.attr("stroke", "#d97706")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", robotX)
.attr("y", robotY + 4)
.attr("text-anchor", "middle")
.attr("font-size", "10px")
.attr("fill", "white")
.text("🤖");
// Sample path visualization
if (phase === "done") {
drawSamplePath(startX, startY);
}
// Formula explanation
const infoX = startX + n * cellSize + 40;
svg.append("text")
.attr("x", infoX)
.attr("y", startY + 20)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Formula:");
svg.append("text")
.attr("x", infoX)
.attr("y", startY + 50)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("dp[i][j] = dp[i-1][j] + dp[i][j-1]");
svg.append("text")
.attr("x", infoX)
.attr("y", startY + 80)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("(paths from above) + (paths from left)");
// Legend
const legend = svg.append("g").attr("transform", `translate(${infoX}, ${startY + 120})`);
legend.append("rect").attr("x", 0).attr("y", 0).attr("width", 15).attr("height", 15).attr("rx", 3).attr("fill", "#dbeafe").attr("stroke", "#3b82f6");
legend.append("text").attr("x", 22).attr("y", 12).attr("font-size", "11px").text("Start cell");
legend.append("rect").attr("x", 0).attr("y", 25).attr("width", 15).attr("height", 15).attr("rx", 3).attr("fill", "#d1fae5").attr("stroke", "#10b981");
legend.append("text").attr("x", 22).attr("y", 37).attr("font-size", "11px").text("End cell");
legend.append("rect").attr("x", 0).attr("y", 50).attr("width", 15).attr("height", 15).attr("rx", 3).attr("fill", "#fef3c7").attr("stroke", "#f59e0b");
legend.append("text").attr("x", 22).attr("y", 62).attr("font-size", "11px").text("Current cell");
// Result
if (phase === "done") {
svg.append("rect")
.attr("x", 80)
.attr("y", 420)
.attr("width", 450)
.attr("height", 60)
.attr("rx", 10)
.attr("fill", "#d1fae5")
.attr("stroke", "#10b981")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", 305)
.attr("y", 458)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.attr("fill", "#10b981")
.text(`✓ ${dp[m-1][n-1]} unique paths from Start to End`);
}
}
function drawSamplePath(startX, startY) {
// Draw one sample path
const path = [[0,0], [0,1], [0,2], [1,2], [2,2], [2,3], [2,4], [3,4]];
svg.append("text")
.attr("x", startX + n * cellSize + 40)
.attr("y", startY + 240)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("One sample path shown");
for (let k = 0; k < path.length - 1; k++) {
const [i1, j1] = path[k];
const [i2, j2] = path[k + 1];
const x1 = startX + j1 * cellSize + (cellSize - 2) / 2;
const y1 = startY + i1 * cellSize + (cellSize - 2) / 2;
const x2 = startX + j2 * cellSize + (cellSize - 2) / 2;
const y2 = startY + i2 * cellSize + (cellSize - 2) / 2;
svg.append("line")
.attr("x1", x1)
.attr("y1", y1)
.attr("x2", x2)
.attr("y2", y2)
.attr("stroke", "#f59e0b")
.attr("stroke-width", 3)
.attr("stroke-opacity", 0.5);
}
}
function step() {
if (phase === "done") return;
if (phase === "init") {
// Initialize base cases
for (let i = 0; i < m; i++) dp[i][0] = 1;
for (let j = 0; j < n; j++) dp[0][j] = 1;
phase = "base";
currentI = 1;
currentJ = 1;
document.getElementById("status").textContent =
"Base cases: first row and column all have 1 path (only one way to reach them)";
render();
return;
}
if (phase === "base") {
phase = "fill";
document.getElementById("status").textContent =
`Filling dp[${currentI}][${currentJ}] = dp[${currentI-1}][${currentJ}] + dp[${currentI}][${currentJ-1}]`;
render();
return;
}
if (phase === "fill") {
dp[currentI][currentJ] = dp[currentI - 1][currentJ] + dp[currentI][currentJ - 1];
document.getElementById("status").textContent =
`dp[${currentI}][${currentJ}] = ${dp[currentI-1][currentJ]} + ${dp[currentI][currentJ-1]} = ${dp[currentI][currentJ]}`;
render();
currentJ++;
if (currentJ >= n) {
currentJ = 1;
currentI++;
if (currentI >= m) {
phase = "done";
document.getElementById("status").textContent =
`✓ Total unique paths = ${dp[m-1][n-1]}`;
render();
}
}
}
}
async function autoRun() {
if (isRunning) {
isRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
return;
}
isRunning = true;
document.getElementById("autoBtn").textContent = "Pause";
while (phase !== "done" && isRunning) {
step();
await new Promise(r => setTimeout(r, 200));
}
isRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
}
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("autoBtn").addEventListener("click", autoRun);
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>