LeedCode finished brushing the data structure in two weeks
1. 73. Matrix zeroing (Java language implementation)
Topic description
Given an mxn matrix, if an element is 0, set all elements in its row and column to 0. Please use an in-place algorithm.
Example 1:
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0] ,[1,0,1]]
Example 2:
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0] ,[0,4,5,0],[0,3,1,0]]
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3 ,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
Recommended Approach: Use an Array of Markers
Ideas and Algorithms:
We can use two marker arrays to record whether there are zero occurrences in each row and each column.
Specifically, we first traverse the array once, and if an element is 0, then set the position of the tag array corresponding to the row and column of the element to true. Finally, we traverse the array again and update the original array with the marked array.
class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
boolean[] row = new boolean[m];
boolean[] col = new boolean[n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
row[i] = col[j] = true;
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (row[i] || col[j]) {
matrix[i][j] = 0;
}
}
}
}
}