Created
April 20, 2012 08:52
-
-
Save zac-xin/2427198 to your computer and use it in GitHub Desktop.
1.7 Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0
This file contains 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
public class SetZero { | |
public static void main(String args[]){ | |
int[][] matrix = { | |
{1, 2, 3 ,4 ,5 ,6}, | |
{12, 13, 0, 15, 16, 17}, | |
{23, 24, 25, 26, 27, 28}, | |
{34, 35, 36, 0, 38, 39}, | |
{45, 46, 47, 48, 49, 50}, | |
{66, 0, 68, 69, 1, 71}, | |
{33, 46, 47, 48, 49, 50} | |
}; | |
printMatrix(matrix); | |
setZero(matrix); | |
System.out.println("After:"); | |
printMatrix(matrix); | |
} | |
public static void setZero(int[][] matrix){ | |
boolean[] row = new boolean[matrix.length]; | |
boolean[] column = new boolean[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){ | |
row[i] = true; | |
column[j] = true; | |
} | |
for(int i = 0; i < matrix.length; i++) | |
for(int j = 0; j < matrix[0].length; j++) | |
if(row[i] || column[j]) | |
matrix[i][j] = 0; | |
} | |
public static void printMatrix(int[][] data){ | |
int i, j; | |
int row = data.length; | |
int column = data[0].length; | |
for(i = 0; i < row; i++){ | |
for(j = 0; j < column; j++) | |
System.out.printf("%3d", data[i][j]); | |
System.out.println(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment