Created
June 21, 2014 21:59
-
-
Save UncleGarden/64c7132968c6c205605a to your computer and use it in GitHub Desktop.
CareerCup 150
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
/** | |
* 1.7 Write an algorithm such that if an element in an MxN matrix is 0, its | |
* entire row and column are set to 0. | |
* | |
* @author Jiateng | |
*/ | |
public class CC1_7 { | |
public static void setZeroes(int[][] matrix) { | |
boolean firstrow = false; | |
boolean firstcolumn = false; | |
//check first row | |
for (int i = 0; i < matrix[0].length; i++) { | |
if (matrix[0][i] == 0) { | |
firstrow = true; | |
break; | |
} | |
} | |
//check first column | |
for (int i = 0; i < matrix.length; i++) { | |
if (matrix[i][0] == 0) { | |
firstcolumn = true; | |
break; | |
} | |
} | |
//if inside matrix has 0; set the related position in firstrow and firstcolumn 0 | |
for (int i = 1; i < matrix.length; i++) { | |
for (int j = 1; j < matrix[0].length; j++) { | |
if (matrix[i][j] == 0) { | |
matrix[i][0] = 0; | |
matrix[0][j] = 0; | |
} | |
} | |
} | |
//if firstrow or firstcolumn is 0, set that column or row all 0 | |
for (int i = 1; i < matrix.length; i++) { | |
for (int j = 1; j < matrix[0].length; j++) { | |
if (matrix[i][0] == 0 || matrix[0][j] == 0) { | |
matrix[i][j] = 0; | |
} | |
} | |
} | |
//set the firstcolumn | |
if (firstcolumn) { | |
for (int i = 0; i < matrix.length; i++) { | |
matrix[i][0] = 0; | |
} | |
} | |
//set the firstrow | |
if (firstrow) { | |
for (int i = 0; i < matrix[0].length; i++) { | |
matrix[0][i] = 0; | |
} | |
} | |
} | |
public static void main(String[] args) { | |
int[][] matrix = new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 0, 1, 2}}; | |
setZeroes(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(" "); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment