Skip to content

Instantly share code, notes, and snippets.

@ajitsing
Created March 30, 2019 18:30
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 ajitsing/2285abc3562f3756c022e9daaa2bd170 to your computer and use it in GitHub Desktop.
Save ajitsing/2285abc3562f3756c022e9daaa2bd170 to your computer and use it in GitHub Desktop.
public class MakeRowColZero {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 0, 9},
{3, 4, 1, 1},
{0, 8, 1, 1},
{7, 9, 1, 1}
};
makeRowColZero(matrix);
printMatrix(matrix);
}
private static void makeRowColZero(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == 0 && !isNeighboursZero(matrix, i, j)) {
addZeros(matrix, i, j);
break;
}
}
}
}
private static boolean isNeighboursZero(int[][] matrix, int row, int col) {
if (row == matrix.length - 1) {
return matrix[row - 1][col] == 0;
} else if (row == 0) {
return matrix[row + 1][col] == 0;
}
return matrix[row - 1][col] == 0 && matrix[row + 1][col] == 0;
}
private static void addZeros(int[][] matrix, int row, int col) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[row][j] = 0;
}
for (int i = 0; i < matrix.length; i++) {
matrix[i][col] = 0;
}
}
private static void printMatrix(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("");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment