73. 矩阵置零
代码
javascript
// 73. 矩阵置零:https://leetcode.cn/problems/set-matrix-zeroes/
// 输入:matrix = [[1,1,1],[1,0,1],[1,1,1]]
// 输出:[[1,0,1],[0,0,0],[1,0,1]]
export function setMatrixZeroes (matrix) {
const m = matrix.length
const n = matrix[0].length
const row = new Array(m).fill(false)
const col = new Array(n).fill(false)
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (matrix[i][j] === 0) {
row[i] = true
col[j] = true
}
}
}
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (row[i] || col[j]) {
matrix[i][j] = 0
}
}
}
}
typescript
// 73. 矩阵置零:https://leetcode.cn/problems/set-matrix-zeroes/
// 输入:matrix = [[1,1,1],[1,0,1],[1,1,1]]
// 输出:[[1,0,1],[0,0,0],[1,0,1]]
export function setMatrixZeroes (matrix: number[][]): void {
const m = matrix.length
const n = matrix[0].length
const row = new Array(m).fill(false)
const col = new Array(n).fill(false)
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (matrix[i][j] === 0) {
row[i] = true
col[j] = true
}
}
}
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (row[i] || col[j]) {
matrix[i][j] = 0
}
}
}
}
测试代码
ts
import { expect, test } from 'vitest'
import { setMatrixZeroes } from './typescript.ts'
import { setMatrixZeroes as setMatrixZeroesJs } from './javascript.js'
test(`setMatrixZeroes`, () => {
const matrix = [[1,1,1],[1,0,1],[1,1,1]]
setMatrixZeroes(matrix)
expect(matrix).toEqual([[1,0,1],[0,0,0],[1,0,1]])
const matrix1 = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
setMatrixZeroes(matrix1)
expect(matrix1).toEqual([[0,0,0,0],[0,4,5,0],[0,3,1,0]])
})
test(`setMatrixZeroesJs`, () => {
const matrix = [[1,1,1],[1,0,1],[1,1,1]]
setMatrixZeroesJs(matrix)
expect(matrix).toEqual([[1,0,1],[0,0,0],[1,0,1]])
const matrix1 = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
setMatrixZeroesJs(matrix1)
expect(matrix1).toEqual([[0,0,0,0],[0,4,5,0],[0,3,1,0]])
})