| 14 | * @return {array} Matrix that has been zeroed, same object as input |
| 15 | */ |
| 16 | export function zeroMatrix(matrix) { |
| 17 | if (!matrix) { |
| 18 | throw new Error("invalid matrix"); |
| 19 | } |
| 20 | if (matrix.length === 0) { |
| 21 | return matrix; |
| 22 | } |
| 23 | |
| 24 | let rows = new Array(matrix.length), |
| 25 | cols = new Array(matrix[0].length); |
| 26 | |
| 27 | rows.fill(false); |
| 28 | cols.fill(false); |
| 29 | |
| 30 | for (let y = 0; y < rows.length; ++y) { |
| 31 | for (let x = 0; x < cols.length; ++x) { |
| 32 | if (matrix[y][x] === 0) { |
| 33 | rows[y] = true; |
| 34 | cols[x] = true; |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | for (let y = 0; y < rows.length; ++y) { |
| 40 | for (let x = 0; x < cols.length; ++x) { |
| 41 | if (rows[y] || cols[x]) { |
| 42 | matrix[y][x] = 0; |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | return matrix; |
| 48 | } |
| 49 | /** |
| 50 | * Time O(nm) where n is the width and m is the height of the matrix |
| 51 | * Space O(nm) |