-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0054_spiral_matrix.html
More file actions
499 lines (420 loc) · 17.5 KB
/
0054_spiral_matrix.html
File metadata and controls
499 lines (420 loc) · 17.5 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spiral Matrix - LeetCode 54</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">#0054</span> Spiral Matrix</h1>
<p><strong>Problem:</strong> Given an m x n matrix, return all elements of the matrix in spiral order.</p>
<p><strong>Pattern:</strong> Simulation with Boundaries - right → down → left → up, shrink bounds</p>
<div class="problem-meta">
<span class="meta-tag">🔲 Matrix</span>
<span class="meta-tag">⏱️ O(m×n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0054_spiral_matrix/0054_spiral_matrix.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Matrix problems work with <strong>2D grids</strong>:</p>
<ul>
<li><strong>Row/Col:</strong> Access elements by [row][col]</li>
<li><strong>Traverse:</strong> Iterate in various patterns</li>
<li><strong>In-place:</strong> Often modify without extra space</li>
<li><strong>Boundaries:</strong> Watch for edge cases</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="visualization">
<svg id="mainSvg"></svg>
</div>
<div class="controls">
<button id="stepBtn">Step</button>
<button id="autoBtn">Auto Run</button>
<button id="resetBtn">Reset</button>
<div class="speed-control">
<label for="speed">Speed:</label>
<input type="range" id="speed" min="100" max="2000" value="500">
</div>
</div>
<div class="status" id="status">Click "Step" to traverse the matrix in spiral order</div>
<div class="variables">
<div class="var-item">
<span class="var-label">Direction:</span>
<span id="dirDisplay">→ Right</span>
</div>
<div class="var-item">
<span class="var-label">Bounds:</span>
<span id="boundsDisplay">top=0, bottom=2, left=0, right=3</span>
</div>
</div>
<div class="result-display">
<h3>Spiral Order:</h3>
<div id="resultList" class="result-list"></div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Spiral Matrix
Problem from LeetCode: https://leetcode.com/problems/spiral-matrix/
Description:
Given an m x n matrix, return all elements of the matrix in spiral order.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
"""
class Solution:
def spiral_order(self, matrix: List[List[int]]) -> List[int]:
"""
Traverse the matrix in spiral order.
Args:
matrix: m x n matrix of integers
Returns:
List[int]: Elements of the matrix in spiral order
"""
if not matrix:
return []
result = []
m, n = len(matrix), len(matrix[0])
# Define the boundaries
top, bottom = 0, m - 1
left, right = 0, n - 1
while top <= bottom and left <= right:
# Traverse right
for j in range(left, right + 1):
result.append(matrix[top][j])
top += 1
# Traverse down
for i in range(top, bottom + 1):
result.append(matrix[i][right])
right -= 1
# Traverse left (if there are rows left)
if top <= bottom:
for j in range(right, left - 1, -1):
result.append(matrix[bottom][j])
bottom -= 1
# Traverse up (if there are columns left)
if left <= right:
for i in range(bottom, top - 1, -1):
result.append(matrix[i][left])
left += 1
return result
def spiral_order_direction(self, matrix: List[List[int]]) -> List[int]:
"""
Alternative implementation using direction changes.
Args:
matrix: m x n matrix of integers
Returns:
List[int]: Elements of the matrix in spiral order
"""
if not matrix:
return []
m, n = len(matrix), len(matrix[0])
result = []
# Direction vectors: right, down, left, up
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
direction_idx = 0
# Starting position
row, col = 0, 0
# Matrix to track visited cells
visited = [[False for _ in range(n)] for _ in range(m)]
for _ in range(m * n):
result.append(matrix[row][col])
visited[row][col] = True
# Calculate next position
next_row = row + directions[direction_idx][0]
next_col = col + directions[direction_idx][1]
# Check if we need to change direction
if (next_row < 0 or next_row >= m or
next_col < 0 or next_col >= n or
visited[next_row][next_col]):
# Change direction
direction_idx = (direction_idx + 1) % 4
next_row = row + directions[direction_idx][0]
next_col = col + directions[direction_idx][1]
row, col = next_row, next_col
return result
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result1 = solution.spiral_order(matrix1)
print(f"Example 1: {result1}") # Expected output: [1,2,3,6,9,8,7,4,5]
# Example 2
matrix2 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
result2 = solution.spiral_order(matrix2)
print(f"Example 2: {result2}") # Expected output: [1,2,3,4,8,12,11,10,9,5,6,7]
# Compare with direction-based approach
print("\nUsing direction-based approach:")
print(f"Example 1: {solution.spiral_order_direction(matrix1)}")
print(f"Example 2: {solution.spiral_order_direction(matrix2)}")
</pre>
</div>
</div>
</div>
<script>
{
const matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
];
const m = matrix.length;
const n = matrix[0].length;
let top = 0, bottom = m - 1, left = 0, right = n - 1;
let result = [];
let visited = Array(m).fill(null).map(() => Array(n).fill(false));
let currentPos = null;
let direction = 0; // 0:right, 1:down, 2:left, 3:up
let directionIndex = 0;
let autoRunning = false;
let autoTimer = null;
const width = 800;
const height = 350;
const svg = d3.select("#mainSvg")
.attr("width", width)
.attr("height", height);
const cellSize = 60;
const startX = (width - n * cellSize) / 2;
const startY = 50;
const directions = ['→ Right', '↓ Down', '← Left', '↑ Up'];
const dirColors = ['#4caf50', '#2196f3', '#ff9800', '#e91e63'];
function draw() {
svg.selectAll("*").remove();
svg.append("text")
.attr("x", width / 2)
.attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text("Spiral Matrix Traversal");
// Draw matrix
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 isVisited = visited[i][j];
const isCurrent = currentPos && currentPos[0] === i && currentPos[1] === j;
const isInBounds = i >= top && i <= bottom && j >= left && j <= right;
svg.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", cellSize - 4)
.attr("height", cellSize - 4)
.attr("rx", 5)
.attr("fill", isCurrent ? "#ffeb3b" :
isVisited ? "#c8e6c9" :
isInBounds ? "#e3f2fd" : "#f5f5f5")
.attr("stroke", isCurrent ? "#f57c00" :
isVisited ? "#4caf50" :
isInBounds ? "#1976d2" : "#bdbdbd")
.attr("stroke-width", isCurrent ? 3 : 2);
svg.append("text")
.attr("x", x + (cellSize - 4) / 2)
.attr("y", y + (cellSize - 4) / 2 + 5)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.attr("fill", isVisited ? "#2e7d32" : "#333")
.text(matrix[i][j]);
}
}
// Draw boundaries
if (top <= bottom && left <= right) {
// Top boundary
svg.append("line")
.attr("x1", startX + left * cellSize - 5)
.attr("y1", startY + top * cellSize - 5)
.attr("x2", startX + (right + 1) * cellSize - 4 + 5)
.attr("y2", startY + top * cellSize - 5)
.attr("stroke", "#e91e63")
.attr("stroke-width", 3);
// Bottom boundary
svg.append("line")
.attr("x1", startX + left * cellSize - 5)
.attr("y1", startY + (bottom + 1) * cellSize - 4 + 5)
.attr("x2", startX + (right + 1) * cellSize - 4 + 5)
.attr("y2", startY + (bottom + 1) * cellSize - 4 + 5)
.attr("stroke", "#e91e63")
.attr("stroke-width", 3);
// Left boundary
svg.append("line")
.attr("x1", startX + left * cellSize - 5)
.attr("y1", startY + top * cellSize - 5)
.attr("x2", startX + left * cellSize - 5)
.attr("y2", startY + (bottom + 1) * cellSize - 4 + 5)
.attr("stroke", "#e91e63")
.attr("stroke-width", 3);
// Right boundary
svg.append("line")
.attr("x1", startX + (right + 1) * cellSize - 4 + 5)
.attr("y1", startY + top * cellSize - 5)
.attr("x2", startX + (right + 1) * cellSize - 4 + 5)
.attr("y2", startY + (bottom + 1) * cellSize - 4 + 5)
.attr("stroke", "#e91e63")
.attr("stroke-width", 3);
}
// Direction indicator
svg.append("rect")
.attr("x", startX + n * cellSize + 20)
.attr("y", startY)
.attr("width", 100)
.attr("height", 40)
.attr("rx", 8)
.attr("fill", dirColors[direction])
.attr("opacity", 0.8);
svg.append("text")
.attr("x", startX + n * cellSize + 70)
.attr("y", startY + 25)
.attr("text-anchor", "middle")
.attr("fill", "white")
.attr("font-weight", "bold")
.text(directions[direction]);
updateResultDisplay();
}
function updateResultDisplay() {
const container = document.getElementById("resultList");
container.innerHTML = result.map((val, i) =>
`<span class="result-item">${val}</span>`
).join(' ');
}
function getNextPositions() {
const positions = [];
if (top > bottom || left > right) return positions;
switch (direction) {
case 0: // Right
for (let col = left; col <= right; col++) {
if (!visited[top][col]) positions.push([top, col]);
}
break;
case 1: // Down
for (let row = top; row <= bottom; row++) {
if (!visited[row][right]) positions.push([row, right]);
}
break;
case 2: // Left
for (let col = right; col >= left; col--) {
if (!visited[bottom][col]) positions.push([bottom, col]);
}
break;
case 3: // Up
for (let row = bottom; row >= top; row--) {
if (!visited[row][left]) positions.push([row, left]);
}
break;
}
return positions;
}
function step() {
if (top > bottom || left > right) {
document.getElementById("status").textContent =
`Complete! Spiral order: [${result.join(", ")}]`;
return false;
}
const positions = getNextPositions();
if (directionIndex < positions.length) {
const [r, c] = positions[directionIndex];
currentPos = [r, c];
visited[r][c] = true;
result.push(matrix[r][c]);
directionIndex++;
document.getElementById("status").textContent =
`Visiting (${r}, ${c}) = ${matrix[r][c]}`;
}
if (directionIndex >= positions.length) {
// Move to next direction
directionIndex = 0;
switch (direction) {
case 0: top++; break;
case 1: right--; break;
case 2: bottom--; break;
case 3: left++; break;
}
direction = (direction + 1) % 4;
document.getElementById("dirDisplay").textContent = directions[direction];
document.getElementById("boundsDisplay").textContent =
`top=${top}, bottom=${bottom}, left=${left}, right=${right}`;
}
draw();
return top <= bottom && left <= right;
}
function reset() {
top = 0; bottom = m - 1; left = 0; right = n - 1;
result = [];
visited = Array(m).fill(null).map(() => Array(n).fill(false));
currentPos = null;
direction = 0;
directionIndex = 0;
autoRunning = false;
if (autoTimer) clearInterval(autoTimer);
document.getElementById("dirDisplay").textContent = "→ Right";
document.getElementById("boundsDisplay").textContent =
`top=0, bottom=${m-1}, left=0, right=${n-1}`;
document.getElementById("status").textContent =
'Click "Step" to traverse the matrix in spiral order';
document.getElementById("autoBtn").textContent = "Auto Run";
draw();
}
function autoRun() {
if (autoRunning) {
autoRunning = false;
clearInterval(autoTimer);
document.getElementById("autoBtn").textContent = "Auto Run";
} else {
autoRunning = true;
document.getElementById("autoBtn").textContent = "Pause";
const speed = 2100 - document.getElementById("speed").value;
autoTimer = setInterval(() => {
if (!step()) {
autoRunning = false;
clearInterval(autoTimer);
document.getElementById("autoBtn").textContent = "Auto Run";
}
}, speed);
}
}
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("autoBtn").addEventListener("click", autoRun);
document.getElementById("resetBtn").addEventListener("click", reset);
draw();
}
</script>
<style>
.result-display {
margin-top: 20px;
padding: 15px;
background: #f8f9fa;
border-radius: 8px;
}
.result-display h3 {
margin: 0 0 10px 0;
}
.result-list {
display: flex;
flex-wrap: wrap;
gap: 5px;
}
.result-item {
background: #4caf50;
color: white;
padding: 5px 12px;
border-radius: 15px;
font-weight: bold;
}
</style>
</body>
</html>