CC189 - 1.8

1.8 Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.

解法一:two bool arrays

void zero(vector<vector<int>> &matrix){
    int n = matrix.size();
    int m = matrix[0].size();
    bool row[n] = {};
    bool col[m] = {};
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            if(matrix[i][j]==0){
                row[i] = true;
                col[j] = true;
            }
        }
    }
    for(int i=0;i<n;i++){
        if(row[i]){
            for(int j=0;j<m;j++){
                matrix[i][j] = 0;
            }
        }
    }
    for(int j=0;j<m;j++){
        if(col[j]){
            for(int i=0;i<n;i++){
                matrix[i][j] = 0;
            }
        }
    }
}

解法二:two bool variables

void zero(vector<vector<int>> &matrix){
    bool row = false;
    bool col = false;
    int n = matrix.size();
    int m = matrix[0].size();
    for(int i=0;i<n;i++){
        if(matrix[i][0]==0){
            col = true;
            break;
        }
    }
    for(int j=0;j<m;j++){
        if(matrix[0][j]==0){
            row = true;
            break;
        }
    }
    for(int i=1;i<n;i++){
        for(int j=1;j<m;j++){
            if(matrix[i][j]==0){
                matrix[i][0] = 0;
                matrix[0][j] = 0;
            }
        }
    }
    for(int i=0;i<n;i++){
        if(matrix[i][0]==0){
            for(int j=1;j<m;j++){
                matrix[i][j] = 0;
            }
        }
    }
    for(int j=0;j<m;j++){
        if(matrix[0][j]==0){
            for(int i=0;i<n;i++){
                matrix[i][j] = 0;
            }
        }
    }
    if(row){
        for(int j=0;j<m;j++){
            matrix[0][j] = 0;
        }
    }
    if(col){
        for(int i=0;i<n;i++){
            matrix[i][0] = 0;
        }
    }
}

https://onlinegdb.com/rkAKv2CjV

猜你喜欢

转载自blog.csdn.net/real_lisa/article/details/89922013
1.8