文章

08 零矩阵

零矩阵

题目描述

编写一种算法,若 M × N 矩阵中某个元素为 0,则将其所在的行与列清零。

示例 1:

1
2
3
4
5
6
7
8
9
10
11
12
输入:
[
  [1,1,1],
  [1,0,1],
  [1,1,1]
]
输出:
[
  [1,0,1],
  [0,0,0],
  [1,0,1]
]

示例 2:

1
2
3
4
5
6
7
8
9
10
11
12
输入:
[
  [0,1,2,0],
  [3,4,5,2],
  [1,3,1,5]
]
输出:
[
  [0,0,0,0],
  [0,4,5,0],
  [0,3,1,0]
]

代码

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
/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
var setZeroes = function (matrix) {
  const rows = matrix.length;
  const columns = matrix[0].length;
  let z_r = {},
    z_c = {};

  // 找0
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < columns; c++) {
      if (matrix[r][c] === 0) {
        !z_r[r] ? (z_r[r] = 1) : z_r[r]++;
        !z_c[c] ? (z_c[c] = 1) : z_c[c]++;
      }
    }
  }

  // 如果没有0直接返回原矩阵
  if (Object.keys(z_r).length === 0) return matrix;

  // 如果有0,辐射横纵轴变0
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < columns; c++) {
      if (z_r[r] > 0 || z_c[c] > 0) matrix[r][c] = 0;
    }
  }

  return matrix;
};
本文由作者按照 CC BY 4.0 进行授权