Skip to content

Instantly share code, notes, and snippets.

@jyhjuzi
Created June 19, 2014 01:15
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 jyhjuzi/af7a2e0a10787a06fb8b to your computer and use it in GitHub Desktop.
Save jyhjuzi/af7a2e0a10787a06fb8b to your computer and use it in GitHub Desktop.
public class Q1_7 {
public static void main(String args[]) {
int a[][] = {
{0, 2, 0, 4},
{5, 6, 7, 8},
{9, 10, 0, 12},
{13, 14, 15, 16}};
process(a);
for(int[] x :a){
for(int integer :x)
System.out.print(integer+" ");
System.out.println(" ");
}
}
public static void process(int[][] matrix) {
boolean firstRow = false;
boolean firstCol = false;
for (int i = 0; i < matrix.length; i++) {
if (matrix[i][0] == 0){
firstCol = true;
break;
}
}
for (int i = 0; i < matrix[0].length; i++) {
if (matrix[0][i] == 0){
firstRow = true;
break;
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == 0) {
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
// check from 1 to ensure not to change the first row
for (int i = 1; i < matrix.length; i++) {
if (matrix[i][0] == 0) {
for (int j = 1; j < matrix[0].length; j++)
matrix[i][j] = 0;
}
}
// check from 1 to ensure not to change the first col
for (int i = 1; i < matrix[0].length; i++) {
if (matrix[0][i] == 0) {
for (int j = 1; j < matrix.length; j++)
matrix[j][i] = 0;
}
}
if (firstRow) {
for (int i = 0; i < matrix[0].length; i++) {
matrix[0][i] = 0;
}
}
if (firstCol) {
for (int i = 0; i < matrix.length; i++) {
matrix[i][0] = 0;
}
}
}
}
@chrislukkk
Copy link

Nice call on the space saving by store the status in first row/column!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment