来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/cells-with-odd-values-in-a-matrix 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

给你一个 m x n 的矩阵,最开始的时候,每个单元格中的值都是 0。
另有一个二维索引数组 indices,indices[i] = [ri, ci] 指向矩阵中的某个位置,其中 ri 和 ci 分别表示指定的行和列(从 0 开始编号)。
对 indices[i] 所指向的每个位置,应同时执行下述增量操作:
ri 行上的所有单元格,加 1 。
ci 列上的所有单元格,加 1 。
给你 m、n 和 indices 。请你在执行完所有 indices 指定的增量操作后,返回矩阵中 奇数值单元格 的数目。

解答

  1. /**
  2. * @param {number} m
  3. * @param {number} n
  4. * @param {number[][]} indices
  5. * @return {number}
  6. */
  7. var oddCells = function(m, n, indices) {
  8. const arr = new Array(m);
  9. for (let i = 0; i < m; i++) {
  10. arr[i] = new Array(n).fill(0);
  11. }
  12. for (let i = 0; i < indices.length; i++) {
  13. const [ x, y ] = indices[i];
  14. if (x < m) {
  15. for (let j = 0; j < n; j++) {
  16. arr[x][j] += 1;
  17. }
  18. }
  19. if (y < n) {
  20. for (let j = 0; j < m; j++) {
  21. arr[j][y] += 1;
  22. }
  23. }
  24. }
  25. let ret = 0;
  26. for (let i = 0; i < m; i++) {
  27. for (let j = 0; j < n; j++) {
  28. if (arr[i][j] % 2) {
  29. ret += 1;
  30. }
  31. }
  32. }
  33. return ret;
  34. };