原文:
Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.
譯文:
寫一個函數處理一個MxN的矩陣,如果矩陣中某個元素為0,那麼把它所在的行和列都置為0.
不能直接進行周遊置0,因為在周遊的過程中可能遇到之前被置0的元素而不是矩陣元素本身。首先進行周遊,記錄下存在0的行和列,然後根據記錄的數組重新周遊矩形進行置0操作。
public static int[][] setZero(int[][] matrix) {
if (matrix == null) {
return null;
}
int row = matrix.length;
int column = 0;
if (row > 0) {
column = matrix[0].length;
}
int[] rows = new int[row];
int[] columns = new int[column];
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if (0 == matrix[i][j]) {
rows[i] = 1;
columns[j] = 1;
}
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if (1 == rows[i] || 1 == columns[j]) {
matrix[i][j] = 0;
}
}
}
return matrix;
}
junit testcase
@Test
public void testSetZero() {
System.out.println("setZero");
int[][] test = null;
int[][] expected = null;
assertArrayEquals(expected, q1_7.setZero(test));
int[][] test1 = {};
int[][] expected1 = {};
assertArrayEquals(expected1, q1_7.setZero(test1));
int[][] test2 = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}};
int[][] expected2 = {{1, 0, 1}, {0, 0, 0}, {1, 0, 1}};
assertArrayEquals(expected2, q1_7.setZero(test2));
int[][] test3 = {{1, 0, 1, 1, 1}, {1, 1, 1, 0, 1}, {1, 1, 1, 1, 1}};
int[][] expected3 = {{0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {1, 0, 1, 0, 1}};
assertArrayEquals(expected3, q1_7.setZero(test3));
}