Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bitcpf
Created June 22, 2014 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitcpf/91139d9c1a058eee5258 to your computer and use it in GitHub Desktop.
Save bitcpf/91139d9c1a058eee5258 to your computer and use it in GitHub Desktop.
/*
Created by bitcpf
*/
public class Replacezero {
public static int[][] setzero(int[][] matrix){
int[] zero_row = new int[matrix.length];
int[] zero_col = new int[matrix[0].length];
for (int i = 0;i < matrix.length; i ++){
for(int j = 0; j< matrix[0].length; j ++){
if(matrix[i][j] == 0){
if(zero_row[i] == 0){
zero_row[i] = 1;
}
if(zero_col[j] == 0){
zero_col[j] = 1;
}
}
}
}
// Set zero for columns
for (int i =0; i<matrix.length; i ++){
if(zero_row[i] == 1){
for(int j = 0; j< matrix[0].length; j++){
matrix[i][j] = 0;
}
}
}
// Set zero for rows
for (int i =0; i<matrix[0].length; i ++){
if(zero_col[i] == 1){
for(int j = 0; j< matrix.length; j++){
matrix[j][i] = 0;
}
}
}
return matrix;
}
public static void printmax(int[][] matrix){
for (int i = 0; i < matrix.length; i ++){
for (int j = 0; j < matrix[0].length; j++){
System.out.print(matrix[i][j]+" ");
}
System.out.println("");
}
}
public static void main(String[] args){
int[][] testmax = new int[][]{{1,2,0,3},{4,1,5,6},{7,8,9,0}};
printmax(testmax);
System.out.println();
printmax(setzero(testmax));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment