Leetcode 73 Solution

This article provides solution to leetcode question 73 (set-matrix-zeroes)

https://leetcode.com/problems/set-matrix-zeroes

Solution

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

        int m = matrix.size();
        int n = matrix[0].size();

        bool isZero1 = matrix[0][0] == 0;
        bool isZero2 = matrix[0][0] == 0;

        for (int i = 1; i < n; i++)
            isZero1 |= matrix[0][i] == 0;
        for (int i = 1; i < m; i++)
            isZero2 |= matrix[i][0] == 0;

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

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

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

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

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

        if (isZero1)
            for (int i = 0; i < n; i++)
                matrix[0][i] = 0;

        if (isZero2)
            for (int i = 0; i < m; i++)
                matrix[i][0] = 0;
    }
};