[C++/Java] Iterating from the Final Query to the First
The problem statement reveals that iterating from the first to the last query allows each subsequent query to overwrite previous values. Consequently, when we r
The problem statement reveals that iterating from the first to the last query allows each subsequent query to overwrite previous values. Consequently, when we reverse this process, iterating from the last query to the first, no query can supersede the one following it. Instead, they only fill values in specific rows or columns if there are entries with a value of 0.\n\nTo facilitate this, we utilize two variables: `rows_filled` and `cols_filled` to track how many rows and columns have been populated so far. When filling a row, the focus is on the number of columns yet to be filled. Values are then filled into these columns, and `rows_filled` is incremented by one. Similarly, when filling a column, the emphasis is on the unpopulated rows. Values are filled into these rows, and `cols_filled` is increased by one.\n\nHowever, we must account for a potential edge case where the queries attempt to fill a row or column multiple times. Since our reverse iteration prevents any query from overwriting a previous one, each row or column can only be filled once. To handle this, we deploy two boolean arrays that track whether a row or column has already been filled.\n\nC++:\n\n```\nclass Solution {\npublic:\n    long long matrixSumQueries(int n, vector<vector<int>>& queries) {\n        int rows_filled = 0, cols_filled = 0;\n        vector<bool> rows(n, 0), cols(n, 0);\n        long sum = 0l;\n        for (int i = queries.size() - 1; i >= 0; i--) {\n            vector<int> q = queries[i];\n            if (q[0] == 0) {\n                if (rows[q[1]]) continue;\n                rows[q[1]] = 1;\n                sum += q[2] * (n - cols_filled);\n                rows_filled++;\n            } else {\n                if (cols[q[1]]) continue;\n                cols[q[1]] = 1;\n                sum += q[2] * (n - rows_filled);\n                cols_filled++;\n            }\n        }\n        return sum;\n    }\n};\n```\n\nJava:\n```\nclass Solution {\n    public long matrixSumQueries(int n, int[][] queries) {\n        int rowsFilled = 0, colsFilled = 0;\n        boolean[] rows = new boolean[n], cols = new boolean[n];\n        long sum = 0l;\n        for (int i = queries.length - 1; i >= 0; i--) {\n            int[] q = queries[i];\n            if (q[0] == 0) {\n                if (rows[q[1]]) continue;\n                rows[q[1]] = true;\n                sum += q[2] * (n - colsFilled);\n                rowsFilled++;\n            } else {\n                if (cols[q[1]]) continue;\n                cols[q[1]] = true;\n                sum += q[2] * (n - rowsFilled);\n                colsFilled++;\n            }\n        }\n        return sum;\n    }\n}\n```
['C', 'Java']