/**
* Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
* click to show follow up.
* Follow up:
* Did you use extra space?
* A straight forward solution using O(m n) space is probably a bad idea.
* A simple improvement uses O(m + n) space, but still not the best solution.
* Could you devise a constant space solution?
*
* 给定m x n矩阵,如果元素为0,则将其整行和整列设置为0。就位。
* 单击以显示“跟进”。
* 跟进:
* 你用了额外的空间吗?
* 使用O(M N)空间的直接解决方案可能是一个坏主意。
* 一个简单的改进使用O(M+N)空间,但仍然不是最好的解决方案。
* 你能想出一个常数空间解吗?
*/
import java.util.ArrayList;
/**
* Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
* click to show follow up.
* Follow up:
* Did you use extra space?
* A straight forward solution using O(m n) space is probably a bad idea.
* A simple improvement uses O(m + n) space, but still not the best solution.
* Could you devise a constant space solution?
*
* 给定m x n矩阵,如果元素为0,则将其整行和整列设置为0。就位。
* 单击以显示“跟进”。
* 跟进:
* 你用了额外的空间吗?
* 使用O(M N)空间的直接解决方案可能是一个坏主意。
* 一个简单的改进使用O(M+N)空间,但仍然不是最好的解决方案。
* 你能想出一个常数空间解吗?
*/
public class Main36 {
public static void main(String[] args) {
int[][] matrix = {
{1,2,3,4,0},
{6,0,8,9,10},
{11,12,0,14,15},
{16,17,18,19,20}
};
setZeroes(matrix);
for (int i=0;i<matrix.length;i++) {
for (int j=0;j<matrix[i].length;j++) {
System.out.print(matrix[i][j] + ", ");
}
System.out.println("");
}
}
public static void setZeroes(int[][] matrix) {
ArrayList<Integer> row = new ArrayList<>();
ArrayList<Integer> colum = new ArrayList<>();
for (int i=0;i<matrix.length;i++) {
for (int j=0;j<matrix[i].length;j++) {
if (matrix[i][j] == 0) {
row.add(i);
colum.add(j);
}
}
}
for (Integer e : row){
for (int i=0;i<matrix[e].length;i++) {
matrix[e][i] = 0;
}
}
for (Integer e : colum) {
for (int j=0;j<matrix.length;j++) {
matrix[j][e] = 0;
}
}
}
}