Created
March 30, 2019 18:30
-
-
Save ajitsing/2285abc3562f3756c022e9daaa2bd170 to your computer and use it in GitHub Desktop.
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 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