《leetCode》:Set Matrix Zeroes

题目

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.


Follow up:
Did you use extra space?
A straight forward solution using O(mn) 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*n的矩阵matrix中,如果matrix[i][j]=0,则将第i行和第j列的全部设置为零;

思路一

暴力搜索法:A simple improvement uses O(m + n) space, but still not the best solution.


#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void setZeroes(int** matrix, int matrixRowSize, int matrixColSize) {
    if(matrix==NULL||matrixRowSize<1||matrixColSize<1){
        return;
    }
    //用来记录哪些行那些列要设为零。
    bool *row=(bool *)malloc(matrixRowSize*sizeof(bool));
    bool *col=(bool *)malloc(matrixColSize*sizeof(bool));
    if(row==NULL||col==NULL){
        exit(EXIT_FAILURE);
    }
    memset(row,true,matrixRowSize*sizeof(bool));
    memset(col,true,matrixColSize*sizeof(bool));
    for(int i=0;i<matrixRowSize;i++){
        for(int j=0;j<matrixColSize;j++){
                if(matrix[i][j]==0){
                    row[i]=false;
                    col[j]=false;
                }

        }
    }
    //将行为零 
    for(int i=0;i<matrixRowSize;i++){
        if(!row[i]){
            for(int j=0;j<matrixColSize;j++){
                matrix[i][j]=0;
            }
        }
    }
    //列变为零 
    for(int i=0;i<matrixColSize;i++){
        if(!col[i]){
            for(int j=0;j<matrixRowSize;j++){
                matrix[j][i]=0;
            }
        }
    }
// for(int i=0;i<matrixRowSize;i++){
// for(int j=0;j<matrixColSize;j++){
// printf("%d ",matrix[i][j]);
// }
// printf("\n");
// }
}
//测试代码如下:
int main(void){
    int row,col;

    while(scanf("%d %d",&row,&col)!=EOF){
        int **matrix=(int **)malloc(row*sizeof(int *));
        if(matrix==NULL){
            exit(EXIT_FAILURE);
        }
        for(int i=0;i<row;i++){
            matrix[i]=(int *)malloc(col*sizeof(int));
            if(matrix[i]==NULL){
                exit(EXIT_FAILURE);
            }
        }
        for(int i=0;i<row;i++){
            for(int j=0;j<col;j++){
                scanf("%d",&matrix[i][j]);
            }
        }
        setZeroes(matrix,1,1);
    }

} 

AC代码如下:
《leetCode》:Set Matrix Zeroes_第1张图片

你可能感兴趣的:(LeetCode,Matrix,zeroes)