-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0073_set_matrix_zeroes.html
More file actions
522 lines (447 loc) · 18.9 KB
/
0073_set_matrix_zeroes.html
File metadata and controls
522 lines (447 loc) · 18.9 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set Matrix Zeroes - LeetCode 73</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">#0073</span> Set Matrix Zeroes</h1>
<p><strong>Problem:</strong> Given an m x n integer matrix, if an element is 0, set its entire row and column to 0's.</p>
<p><strong>Pattern:</strong> Use first row/column as markers - O(1) space solution</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/0073_set_matrix_zeroes/0073_set_matrix_zeroes.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="700">
</div>
</div>
<div class="status" id="status">Click "Step" to set matrix zeroes in-place</div>
<div class="variables">
<div class="var-item">
<span class="var-label">Phase:</span>
<span id="phaseDisplay">1. Mark zeros in first row/col</span>
</div>
<div class="var-item">
<span class="var-label">First Row Zero:</span>
<span id="rowZeroDisplay">false</span>
</div>
<div class="var-item">
<span class="var-label">First Col Zero:</span>
<span id="colZeroDisplay">false</span>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Set Matrix Zeroes
Problem from LeetCode: https://leetcode.com/problems/set-matrix-zeroes/
Description:
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.
You must do it in place.
Example 1:
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
Example 2:
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
"""
class Solution:
def set_zeroes(self, matrix: List[List[int]]) -> None:
"""
Set entire row and column to 0 for each 0 element in the matrix.
Modifies the matrix in-place with O(1) extra space.
Args:
matrix: m x n integer matrix
"""
if not matrix or not matrix[0]:
return
m, n = len(matrix), len(matrix[0])
# Use first row and first column as markers
first_row_has_zero = False
first_col_has_zero = False
# Check if first row has any zeroes
for j in range(n):
if matrix[0][j] == 0:
first_row_has_zero = True
break
# Check if first column has any zeroes
for i in range(m):
if matrix[i][0] == 0:
first_col_has_zero = True
break
# Use first row and column as markers for zeroes in other cells
for i in range(1, m):
for j in range(1, n):
if matrix[i][j] == 0:
matrix[i][0] = 0 # Mark the row
matrix[0][j] = 0 # Mark the column
# Zero out marked rows (except first row)
for i in range(1, m):
if matrix[i][0] == 0:
for j in range(1, n):
matrix[i][j] = 0
# Zero out marked columns (except first column)
for j in range(1, n):
if matrix[0][j] == 0:
for i in range(1, m):
matrix[i][j] = 0
# Zero out first row if needed
if first_row_has_zero:
for j in range(n):
matrix[0][j] = 0
# Zero out first column if needed
if first_col_has_zero:
for i in range(m):
matrix[i][0] = 0
def set_zeroes_using_sets(self, matrix: List[List[int]]) -> None:
"""
Alternative implementation using sets to track rows and columns.
Uses O(m+n) extra space but easier to understand.
Args:
matrix: m x n integer matrix
"""
if not matrix or not matrix[0]:
return
m, n = len(matrix), len(matrix[0])
# Track which rows and columns need to be zeroed
zero_rows = set()
zero_cols = set()
# Find all zeroes in the matrix
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
zero_rows.add(i)
zero_cols.add(j)
# Zero out marked rows
for row in zero_rows:
for j in range(n):
matrix[row][j] = 0
# Zero out marked columns
for col in zero_cols:
for i in range(m):
matrix[i][col] = 0
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
matrix1 = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]
print(f"Original matrix 1:")
for row in matrix1:
print(row)
solution.set_zeroes(matrix1)
print(f"\nAfter setting zeroes:")
for row in matrix1:
print(row)
# Expected output: [[1,0,1],[0,0,0],[1,0,1]]
# Example 2
matrix2 = [[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]]
print(f"\nOriginal matrix 2:")
for row in matrix2:
print(row)
solution.set_zeroes(matrix2)
print(f"\nAfter setting zeroes:")
for row in matrix2:
print(row)
# Expected output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
# Test alternative approach with a new matrix
matrix3 = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]
solution.set_zeroes_using_sets(matrix3)
print(f"\nUsing sets approach:")
for row in matrix3:
print(row)
# Expected output: [[1,0,1],[0,0,0],[1,0,1]]
</pre>
</div>
</div>
</div>
<script>
const originalMatrix = [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
];
let matrix = JSON.parse(JSON.stringify(originalMatrix));
const m = matrix.length;
const n = matrix[0].length;
let phase = 1; // 1: check first row/col, 2: mark, 3: set zeros, 4: handle first row/col
let stepIndex = 0;
let firstRowZero = false;
let firstColZero = false;
let autoRunning = false;
let autoTimer = null;
const width = 800;
const height = 380;
const svg = d3.select("#mainSvg")
.attr("width", width)
.attr("height", height);
const cellSize = 55;
function draw(highlights = []) {
svg.selectAll("*").remove();
// Original
svg.append("text")
.attr("x", 120)
.attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text("Original");
drawMatrix(originalMatrix, 50, 50, [], true);
// Arrow
svg.append("text")
.attr("x", width / 2)
.attr("y", 150)
.attr("text-anchor", "middle")
.attr("font-size", "30px")
.text("→");
// Current
svg.append("text")
.attr("x", width - 120)
.attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text("Processing");
drawMatrix(matrix, width - 50 - n * cellSize, 50, highlights, false);
// Phase indicator
const phaseY = 280;
const phases = [
"1. Check first row/col",
"2. Mark zeros",
"3. Set zeros from markers",
"4. Handle first row/col"
];
phases.forEach((p, idx) => {
svg.append("rect")
.attr("x", 50 + idx * 175)
.attr("y", phaseY)
.attr("width", 165)
.attr("height", 35)
.attr("rx", 5)
.attr("fill", phase === idx + 1 ? "#4caf50" : "#e0e0e0")
.attr("stroke", phase === idx + 1 ? "#2e7d32" : "#bdbdbd");
svg.append("text")
.attr("x", 50 + idx * 175 + 82)
.attr("y", phaseY + 22)
.attr("text-anchor", "middle")
.attr("font-size", "11px")
.attr("fill", phase === idx + 1 ? "white" : "#666")
.text(p);
});
// Legend for markers
svg.append("text")
.attr("x", 50)
.attr("y", phaseY + 60)
.attr("font-size", "12px")
.attr("fill", "#666")
.text("🟡 Marker in first row/col | 🔴 Will be set to 0 | 🟢 Processed");
}
function drawMatrix(mat, x, y, highlights, isOriginal) {
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
const cellX = x + j * cellSize;
const cellY = y + i * cellSize;
const isHighlight = highlights.some(h => h[0] === i && h[1] === j);
const isMarker = !isOriginal && (i === 0 || j === 0) && mat[i][j] === 0;
const isZero = mat[i][j] === 0;
let fill = "#f5f5f5";
let stroke = "#bdbdbd";
if (!isOriginal) {
if (isHighlight) {
fill = "#ffeb3b";
stroke = "#f57c00";
} else if (isMarker) {
fill = "#fff3e0";
stroke = "#ff9800";
} else if (isZero && !isOriginal) {
fill = "#ffcdd2";
stroke = "#e53935";
} else if (mat[i][j] !== originalMatrix[i][j]) {
fill = "#c8e6c9";
stroke = "#4caf50";
}
} else if (isZero) {
fill = "#ffcdd2";
stroke = "#e53935";
}
svg.append("rect")
.attr("x", cellX)
.attr("y", cellY)
.attr("width", cellSize - 4)
.attr("height", cellSize - 4)
.attr("rx", 5)
.attr("fill", fill)
.attr("stroke", stroke)
.attr("stroke-width", isHighlight ? 3 : 2);
svg.append("text")
.attr("x", cellX + (cellSize - 4) / 2)
.attr("y", cellY + (cellSize - 4) / 2 + 5)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.text(mat[i][j]);
}
}
}
function step() {
switch (phase) {
case 1: // Check first row/col for zeros
if (stepIndex < n) {
if (matrix[0][stepIndex] === 0) firstRowZero = true;
draw([[0, stepIndex]]);
document.getElementById("status").textContent =
`Checking first row [0][${stepIndex}] = ${matrix[0][stepIndex]}`;
stepIndex++;
} else if (stepIndex < n + m) {
const i = stepIndex - n;
if (matrix[i][0] === 0) firstColZero = true;
draw([[i, 0]]);
document.getElementById("status").textContent =
`Checking first col [${i}][0] = ${matrix[i][0]}`;
stepIndex++;
}
if (stepIndex >= n + m) {
phase = 2;
stepIndex = 0;
document.getElementById("phaseDisplay").textContent = "2. Mark zeros";
}
document.getElementById("rowZeroDisplay").textContent = firstRowZero.toString();
document.getElementById("colZeroDisplay").textContent = firstColZero.toString();
return true;
case 2: // Mark zeros in first row/col
const total = (m - 1) * (n - 1);
if (stepIndex < total) {
const i = Math.floor(stepIndex / (n - 1)) + 1;
const j = (stepIndex % (n - 1)) + 1;
if (matrix[i][j] === 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
document.getElementById("status").textContent =
`Found 0 at [${i}][${j}]: marked [${i}][0] and [0][${j}]`;
} else {
document.getElementById("status").textContent =
`Checking [${i}][${j}] = ${matrix[i][j]}`;
}
draw([[i, j]]);
stepIndex++;
}
if (stepIndex >= total) {
phase = 3;
stepIndex = 0;
document.getElementById("phaseDisplay").textContent = "3. Set zeros from markers";
}
return true;
case 3: // Set zeros based on markers
const total3 = (m - 1) * (n - 1);
if (stepIndex < total3) {
const i = Math.floor(stepIndex / (n - 1)) + 1;
const j = (stepIndex % (n - 1)) + 1;
if (matrix[i][0] === 0 || matrix[0][j] === 0) {
matrix[i][j] = 0;
document.getElementById("status").textContent =
`Setting [${i}][${j}] = 0 (marker found)`;
}
draw([[i, j]]);
stepIndex++;
}
if (stepIndex >= total3) {
phase = 4;
stepIndex = 0;
document.getElementById("phaseDisplay").textContent = "4. Handle first row/col";
}
return true;
case 4: // Handle first row/col
if (firstRowZero && stepIndex < n) {
matrix[0][stepIndex] = 0;
draw([[0, stepIndex]]);
document.getElementById("status").textContent =
`Setting first row [0][${stepIndex}] = 0`;
stepIndex++;
return true;
} else if (firstColZero && stepIndex < n + m) {
const i = stepIndex - n;
if (i < m) {
matrix[i][0] = 0;
draw([[i, 0]]);
document.getElementById("status").textContent =
`Setting first col [${i}][0] = 0`;
stepIndex++;
return true;
}
}
document.getElementById("status").textContent = "Complete! Matrix zeroes set.";
draw();
return false;
}
return false;
}
function reset() {
matrix = JSON.parse(JSON.stringify(originalMatrix));
phase = 1;
stepIndex = 0;
firstRowZero = false;
firstColZero = false;
autoRunning = false;
if (autoTimer) clearInterval(autoTimer);
document.getElementById("phaseDisplay").textContent = "1. Check first row/col";
document.getElementById("rowZeroDisplay").textContent = "false";
document.getElementById("colZeroDisplay").textContent = "false";
document.getElementById("status").textContent = 'Click "Step" to set matrix zeroes in-place';
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>
</body>
</html>