Leetcode 3033. Modify the Matrix
You are given a 2D integer matrix matrix
and an integer x
. You need to return a new matrix such that every element in the new matrix is the sum of all elements in the original matrix except the ones that are in the same row or in the same column as the original element.
Here is a more formal description:
matrix[i][j]
should be replaced with the sum of all elements in matrix
except for those elements in i
-th row and in j
-th column.#include <vector>
#include <numeric>
#include <iostream>
std::vector<std::vector<int>> modifyMatrix(const std::vector<std::vector<int>>& matrix, int x) {
int rows = matrix.size();
if (rows == 0) return {};
int cols = matrix[0].size();
if (cols == 0) return {};
// Calculate the sum of each row and each column
std::vector<int> rowSum(rows, 0), colSum(cols, 0);
int totalSum = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
rowSum[i] += matrix[i][j];
colSum[j] += matrix[i][j];
totalSum += matrix[i][j];
}
}
// Create the resulting matrix
std::vector<std::vector<int>> result(rows, std::vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
// Subtract the sum of current row and column, then add back the current element as it's excluded twice
result[i][j] = totalSum - rowSum[i] - colSum[j] + matrix[i][j];
}
}
return result;
}
// Function for printing the matrix (for debugging purposes)
void printMatrix(const std::vector<std::vector<int>>& matrix) {
for (const auto& row : matrix) {
for (int val : row) {
std::cout << val << " ";
}
std::cout << std::endl;
}
}
int main() {
std::vector<std::vector<int>> matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
std::vector<std::vector<int>> result = modifyMatrix(matrix, 0);
printMatrix(result);
return 0;
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?