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

版权声明: 本文为 InfoQ 作者【Lee Chen】的原创文章。
原文链接:【http://xie.infoq.cn/article/fe439e6f4731c008632fa6f1f】。文章转载请联系作者。

原题链接:73. 矩阵置零
解题思路:
遍历矩阵,找到所有为0的坐标,将它们都存入栈。
从栈中依次弹出坐标,并将对应的行、列元素都设置为 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; } }};
版权声明: 本文为 InfoQ 作者【Lee Chen】的原创文章。
原文链接:【http://xie.infoq.cn/article/fe439e6f4731c008632fa6f1f】。文章转载请联系作者。
还未添加个人签名 2018.08.29 加入
还未添加个人简介

促进软件开发及相关领域知识与创新的传播
京公网安备 11010502039052号


评论