Last active
August 28, 2018 07:32
-
-
Save lienista/4135ba53826da3ebe89e3d7d545a8f75 to your computer and use it in GitHub Desktop.
Algorithms in Javascript: CTCI 1.8 Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const zeroMatrix = (m) => { | |
| const sizeY = m.length, | |
| sizeX = m[0].length; | |
| let charMap = new Map(); | |
| for(let r=0; r<sizeY; r++){ | |
| for(let c=0; c<sizeX; c++){ | |
| if(m[r][c] === 0) { | |
| charMap.set(r, c); | |
| } | |
| } | |
| } | |
| for (let [key, value] of charMap.entries()) { | |
| for(let r=0; r<sizeX; r++){ | |
| m[r][value] = 0; | |
| } | |
| for(let c=0; c<sizeY; c++){ | |
| m[key][c] = 0; | |
| } | |
| } | |
| return m; | |
| } | |
| var a = [[1,2,0], | |
| [4,5,6], | |
| [0,8,9]]; | |
| var za = zeroMatrix(a); | |
| console.log(za); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment