MxN Matrix 0 element makes row & column 0s
var matrix = [
[ 2, 3, 1, 4, 5 ],
[ 4, 6, 0, 9, 8 ],
[ 3, 2, 1, 8, 2 ],
[ 6, 3, 4, 7, 6 ],
[ 8, 5, 7, 2, 1 ]
],
saveRows = [],
saveColumns = [],
i,
j;
var onceRowLength = matrix.length;
var onceColumnLength = matrix[0].length;
function displayMatrix(matrix) {
for ( i = 0; i < onceRowLength; i++ ) {
for ( j = 0; j < onceColumnLength; j++ ) {
document.writeln(matrix[i][j]);
}
document.writeln('<br />');
}
}
function saveRowsAndColumns(matrix) {
for ( i = 0; i < onceRowLength; i++ ) {
for ( j = 0; j < onceColumnLength; j++ ) {
if ( matrix[i][j] == 0) {
saveRows[i] = true;
saveColumns[j] = true;
}
}
}
}
function zeroTheMatrix(matrix) {
for ( i = 0; i < onceRowLength; i++) {
for ( j = 0; j < onceColumnLength; j++ ) {
if ( saveRows[i] || saveColumns[j] ) {
matrix[i][j] = 0;
}
}
}
}
displayMatrix(matrix);
saveRowsAndColumns(matrix);
zeroTheMatrix(matrix);
document.writeln('<br />');
displayMatrix(matrix);
This entry was posted on Monday, August 3rd, 2015 at 1:40 pm and is filed under Algorithms, Interview Questions, JavaScript. You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.