当前位置:网站首页>Interview question 01.08 Zero matrix

Interview question 01.08 Zero matrix

2022-07-04 22:02:00 Mr Gao

Interview questions 01.08. Zero matrix

Write an algorithm , if M × N An element in the matrix is 0, The row and column in which it is located are cleared .

Example 1:

Input :
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output :
[
[1,0,1],
[0,0,0],
[1,0,1]
]

Example 2:

Input :
[
[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]
]

void dfs(int **matrix,int n ,int m,int row,int col,int *rrow,int* rcol ){
    
     
     int i;
      // printf("- %d %d ",col,row);
    if(rrow[row]==1){
    
        rrow[row]=0;
                for(i=0;i<m;i++){
    
                    if(matrix[row][i]!=0){
    
                        matrix[row][i]=-999;
                    }
                    else{
    
                        if(rrow[row]==1||rcol[i]==1){
    
                             dfs(matrix,n , m, row, i,rrow,rcol);

                        }
                       
                    }
                }
       }
   if(rcol[col]==1){
    
       rcol[col]=0;
        for(i=0;i<n;i++){
    
            if(matrix[i][col]!=0){
    
                matrix[i][col]=-999;
            }
            else{
    
                  if(rrow[i]==1||rcol[col]==1){
    
                dfs(matrix, n , m, i, col,rrow,rcol);
                  }
            }
        }
   }

}


void setZeroes(int** matrix, int matrixSize, int* matrixColSize){
    
    int n=matrixSize;
    int m=matrixColSize[0];
    int *rrow=(int *)malloc(sizeof(int)*n);
    int *rcol=(int *)malloc(sizeof(int)*m);
    
    int i,j;
    for(i=0;i<n;i++){
    
        rrow[i]=1;
    }
     for(i=0;i<m;i++){
    
        rcol[i]=1;
    }
    printf("df");

    for(i=0;i<n;i++){
    
        if(rrow[i]==1){
    

        for(j=0;j<m;j++){
    
             
            if(matrix[i][j]==0){
    
                       dfs(matrix,n , m, i, j,rrow,rcol);
                       break;
                      }
              }
         }
    }

    for(i=0;i<n;i++){
    
      

        for(j=0;j<m;j++){
    
             
            if(matrix[i][j]==-999){
    
                      matrix[i][j]=0;
                      }
              }
         
    }
}

There is also a relatively simple algorithm , Mark appears 0 Rows and columns of , Then traverse the two arrays that store rows and columns , This method is relatively simple

原网站

版权声明
本文为[Mr Gao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207042123507489.html