Skip to content

LeetCode题解:73. 矩阵置零,栈,JavaScript,详细注释 #333

Description

@chencl1986

原题链接:73. 矩阵置零

解题思路:

  1. 遍历矩阵,找到所有为0的坐标,将它们都存入栈。
  2. 从栈中依次弹出坐标,并将对应的行、列元素都设置为0。
/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
var setZeroes = function (matrix) {
  let stack = []; // 使用栈存储矩阵中为0的坐标
  let m = matrix.length; // 缓存矩阵的行数
  let n = matrix[0].length; // 缓存矩阵的列数

  // 遍历矩阵的每个坐标
  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      // 如果当前位置为0,将坐标存入栈
      if (matrix[i][j] === 0) {
        stack.push([i, j]);
      }
    }
  }

  // 将所有坐标的行和列都设为0
  while (stack.length) {
    // 每次取出一个坐标
    const [x, y] = stack.pop();

    // 将当前坐标所在的列设为0
    for (let i = 0; i < m; i++) {
      matrix[i][y] = 0;
    }

    // 将当前坐标所在的行设为0
    for (let i = 0; i < n; i++) {
      matrix[x][i] = 0;
    }
  }
};

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions