Skip to content

Instantly share code, notes, and snippets.

@daifu
Created May 6, 2013 03:35
Show Gist options
  • Save daifu/5523227 to your computer and use it in GitHub Desktop.
Save daifu/5523227 to your computer and use it in GitHub Desktop.
Set Matrix Zeroes
/*
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Algorithm:
1. No need extra space and it has O(n*m) complexity in time
2. Go throught the matrix and if it meets 0, then set its row and col to ZERO
3. Once complete, then go throught the matrix again and change ZERO to 0;
*/
public class Solution {
final int ZERO = 999999;
public void setZeroes(int[][] matrix) {
// Start typing your Java solution below
// DO NOT write main() function
int row = matrix.length;
if(row == 0) return;
int col = matrix[0].length;
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
if(matrix[i][j] == 0) {
setRow(matrix, i, ZERO);
setCol(matrix, j, ZERO);
}
}
}
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
if(matrix[i][j] == ZERO) {
matrix[i][j] = 0;
}
}
}
return;
}
public void setRow(int[][] matrix, int row, int zero) {
for(int i = 0; i < matrix[0].length; i++) {
if(matrix[row][i] != 0) matrix[row][i] = zero;
}
}
public void setCol(int[][] matrix, int col, int zero) {
for(int i = 0; i < matrix.length; i++) {
if(matrix[i][col] != 0) matrix[i][col] = zero;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment