1.7 Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.
import java.util.ArrayList;
public class Solution{
//time complexity:O(m*n), space complexity:O(m+n)(worst complexity)
public static void setMatrix(int[][] M){
int[] c = new int[M.length];//
//record row or col need to be set with 0
//space complexty:O(m+n)
ArrayList<Integer> row = new ArrayList<Integer>();
ArrayList<Integer> col = new ArrayList<Integer>();
//time complexity:O(m*n)
for(int i=0;i < M.length;i++)
for(int j=0;j < M[i].length;j++){
if(M[i][j] != 0)
continue;
if(!row.contains(i))
row.add(i);
if(!col.contains(j))
col.add(j);
}
//time complexity:O(m*n)
//set row with 0
int index = 0;
for(int i=0;i < row.size();i++){
index = row.get(i);
for(int j=0;j < M[index].length;j++)
M[index][j] = 0;
}
//time complexity:O(n*m)
//set column with 0
for(int i=0;i < col.size();i++){
index = col.get(i);
for(int j=0;j < M.length;j++)
M[j][index] = 0;
}
}
private static void printM(int[][] M){
for(int i=0;i < M.length;i++){
for(int j=0;j < M[i].length;j++)
System.out.print(M[i][j]+" ");
System.out.println();
}
}
public static void main(String[] args){
int[][] M = new int[][]{
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
};
Solution.printM(M);
Solution.setMatrix(M);
System.out.println();//
Solution.printM(M);
}
}
当前较优解
最坏情况下:时间复杂度:O(m*n)
空间复杂度:O(m+n)