面试题 01.08

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

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] ]

Solutions

  1. straight forward

  2. use the first column/row as inplace marker.

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        if (!matrix.size()) return;
        int m = matrix.size(), n = matrix[0].size();

        bool czero1 = false, rzero1 = false;
        if (matrix[0][0] == 0)
            czero1 = rzero1 = true;
        else {
            for (int j = 1; j < n; j++)
                if (matrix[0][j] == 0) {
                    rzero1 = true; break;
                }
            for (int i = 1; i < m; i++)
                if (matrix[i][0] == 0) {
                    czero1 = true; break;
                }
        }

        for (int i = 1; i < m; i++)
            for (int j = 1; j < n; j++)
                if (matrix[i][j] == 0)
                    matrix[0][j] = matrix[i][0] = 0;

        for (int i = 1; i < m; i++)
            for (int j = 1; j < n; j++)
                if (!matrix[0][j] || !matrix[i][0])
                    matrix[i][j] = 0;

        if (rzero1)
            for (int j = 0; j < n; j++)
                matrix[0][j] = 0;
        if (czero1)
            for (int i = 0; i < m; i++)
                matrix[i][0] = 0;
    }
};

Last updated