1.7编写一个算法,若M*N矩阵中某个元素为0,则将其所在的行与列清零。

思路:先遍历一遍找到0,然后将其他们的行与列分别记下来。接着再把相应行列置0。

public void setZeros(int[][] matrix)
{
    boolean[] row = new boolean[matrix.length];
    boolean[] column = new boolean[matrix[0].length];
    
    //确认哪些行哪些列需要置0
    for(int i = 0; i < matrix.length; i++)
    {
        for(int j = 0; j < matrix[0].length; j++)
        {
            if (matrix[i][j] == 0)
            {
                row[i] = true;
                column[j] = true;
            }
        }
    }
    
    //置0
    for(int i = 0; i < matrix.length; i++)
    {
        for(int j = 0; j < matrix[0].length; j++)
        {
            if (row[i] || column[j])
            {
                matrix[i][j] = 0;
            }
        }
    }   
}