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);

Leave a Reply

You must be logged in to post a comment.