There is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each indices[i] = [ri, ci] represents a 0-indexed location to perform some increment operations on the matrix.
For each location indices[i], do both of the following:
Increment all the cells on row ri.
Increment all the cells on column ci.
Given m, n, and indices, return the number of odd-valued cells in the matrix after applying the increment to all locations in indices.
Example 1:
Input: m = 2, n = 3, indices = [[0,1],[1,1]]
Output: 6
Explanation: Initial matrix = [[0,0,0],[0,0,0]].
After applying first increment it becomes [[1,2,1],[0,1,0]].
The final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers.
Example 2:
Input: m = 2, n = 2, indices = [[1,1],[0,0]]
Output: 0
Explanation: Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix.
Constraints:
1 <= m, n <= 50
1 <= indices.length <= 100
0 <= ri < m
0 <= ci < n
Follow up: Could you solve this in O(n + m + indices.length) time with only O(n + m) extra space?
We create a matrix g to store the results of the operations. For each pair (ri,ci) in indices, we add 1 to all elements in the rith row and the cith column of the matrix.
After the simulation, we traverse the matrix and count the number of odd numbers.
The time complexity is O(indices.length×(m+n)+mn), and the space complexity is O(mn).
We use row array row and column array col to record the number of times each row and column are increased. For each pair (ri,ci) in indices, we add 1 to row[ri] and col[ci] respectively.
After the operation, we can calculate that the count at position (i,j) is row[i]+col[j]. We traverse the matrix and count the number of odd numbers.
The time complexity is O(indices.length+mn), and the space complexity is O(m+n).
We notice that only when exactly one of row[i] and col[j] is odd, the number at position (i,j) in the matrix will be odd.
We count the number of odd numbers in row, denoted as cnt1; the number of odd numbers in col, denoted as cnt2. Then the final number of odd numbers is cnt1×(n−cnt2)+cnt2×(m−cnt1).
The time complexity is O(indices.length+m+n), and the space complexity is O(m+n).