99Ms-runtime ,Java based solution,Easy to understand involves two matrix operations


  • 0
    P

    class Solution {
    static int [][]inmatr(int[][]mat1,int[][]mat2)
    {
    int r=mat2.length;
    int c=mat2[0].length;
    for(int x=0;x<r;x++)
    {
    for(int y=0;y<c;y++)
    {
    mat1[x][y]=mat2[x][y];
    }
    }
    return mat1;
    }
    public void setZeroes(int[][] matrix) {
    int rows = matrix.length;
    int cols = matrix[0].length;
    int[][]mat1=new int[rows][cols];
    int[][]inmat=inmatr(mat1,matrix);
    for(int x=0;x<rows;x++)
    {
    for(int y=0;y<cols;y++)
    {
    if(matrix[x][y]==0)
    {
    int r1=x+1;
    int c1 = y+1;
    for(int x1=0;x1<r1;x1++)
    {
    for(int y1=y;y1<c1;y1++)
    {
    for(int x2=x1;x2<rows;x2++)
    {
    matrix[x2][y1]=0;
    }
    }
    }
    }
    }
    }
    for(int k=0;k<rows;k++)
    {
    for(int t=0;t<cols;t++)
    {
    if(inmat[k][t]==0)
    {
    int k1=k;
    for(int k2=k1;k2<=k1;k2++)
    {
    for(int c2=0;c2<cols;c2++)
    {
    inmat[k2][c2]=0;
    }
    }
    }
    }
    }
    for(int k=0;k<rows;k++)
    {
    for(int t=0;t<cols;t++)
    {
    if((inmat[k][t]==0&&matrix[k][t]!=0)||((inmat[k][t]!=0&&matrix[k][t]==0)))
    {
    inmat[k][t]=0;
    }
    }
    }
    for(int k=0;k<rows;k++)
    {
    for(int t=0;t<cols;t++)
    {
    matrix[k][t]=inmat[k][t];
    }
    }
    }
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.