73. Set Matrix Zeroes
Tags:
Medium
Skills:
Matrix
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Bài toán yêu cầu, nếu một phần tử trong matrix là 0, hãy set toàn bộ row và col chứa phần tử đó thành 0, thực hiện in-place (không dùng thêm SC)
Approach
marker (đánh dấu) cho các dòng/ cột cần set về 0Các bước chính
Solution
1/**
2 Do not return anything, modify matrix in-place instead.
3 */
4function setZeroes(matrix: number[][]): void {
5 let rows = matrix.length;
6 let cols = matrix[0].length;
7 let first_row_zero = false;
8 let first_col_zero = false;
9
10 for (let i = 0; i < rows; i++) {
11 if (matrix[i][0] === 0) {
12 first_col_zero = true;
13 break;
14 }
15 }
16
17 for (let i = 0; i < cols; i++) {
18 if (matrix[0][i] === 0) {
19 first_row_zero = true;
20 break;
21 }
22 }
23
24 for (let i = 1; i < rows; i++) {
25 for (let j = 1; j < cols; j++) {
26 if (matrix[i][j] === 0) {
27 matrix[i][0] = 0;
28 matrix[0][j] = 0;
29 }
30 }
31 }
32
33 for (let i = 1; i < rows; i++) {
34 for (let j = 1; j < cols; j++) {
35 if (matrix[i][0] === 0 || matrix[0][j] === 0) {
36 matrix[i][j] = 0
37 }
38 }
39 }
40
41 if (first_row_zero) {
42 for (let i = 0; i < cols; i++) {
43 matrix[0][i] = 0
44 }
45 }
46
47 if (first_col_zero) {
48 for (let i = 0; i < rows; i++) {
49 matrix[i][0] = 0;
50 }
51 }
52};matrix[i] = 0 và matrix[j] = 0 Nếu bạn gặp một phần tử matrix[i][j] === 0 , bạn cần đặt toàn bộ hoàng i và toàn bộ cột j thành 0
Nếu bạn làm ngay lặp tức (set tất cả các phần tử cùng hàng/ cột thành 0 ngay khi gặp 0) bạn sẽ làm sai kết quả vì những số 0 mới này sẽ ảnh hưởng đến lần kiểm tra tiếp theo (tao ra hiệu ứng domino không mong muốn)