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.

http://www.lintcode.com/en/problem/set-matrix-zeroes/#

Discussion

用第一行和第一列作标志位。
1.先确定第一行和第一列是否需要清零
2.扫描剩下的矩阵元素,如果遇到了0,就将对应的第一行和第一列上的元素赋值为0
3.根据第一行和第一列的信息,已经可以讲剩下的矩阵元素赋值为结果所需的值了
4.根据1中确定的状态,处理第一行和第一列。

Solution

class Solution {
public:
    /**
     * @param matrix: A list of lists of integers
     * @return: Void
     */
    void setZeroes(vector<vector<int> > &matrix) {
        if(matrix.empty()) return;
        int m = matrix.size(); //row
        int n = matrix[0].size(); // col
        bool zero_row = false;
        bool zero_col = false;
        //chcek first col
        for(int i=0; i<m; i++) {
            if(matrix[i][0] == 0) {
                zero_col = true;
                break;
            }
        }
        //check first row
        for(int j=0; j<n; j++) {
            if(matrix[0][j] ==0) {
                zero_row = true;
                break;
            }
        }
        //use the first row as the sign if there is 0 in some column
        //us3 the first column as the sign if there is 0 in some row
        for(int i=1; i<m; i++) {
            for(int j=1; j<n; j++) {
                if(matrix[i][j] == 0) {
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        //update matrix with the signs in the first col and row
        for(int i=1; i<m; i++) {
            for(int j=1; j<n; j++) {
                if(matrix[0][j] == 0 || matrix[i][0] ==0) {
                    matrix[i][j] = 0;
                }
            }
        }
        //update the first row and column
        if(zero_row) {
            for(int j=0; j<n; j++) {
                matrix[0][j] = 0;
            }
        }
        if(zero_col) {
            for(int i=0; i<m; i++) {
                matrix[i][0] = 0;
            }
        }
    }
};

results matching ""

    No results matching ""