求邻居二维数组的总和

时间:2019-06-15 15:49:56

标签: javascript multidimensional-array time-complexity big-o neighbours

编写一个函数,其中函数接受2个输入矩阵(例如2维数组)和索引:例如[row,col] 此函数应返回所有第二个输入邻居的和(上,下,左,右,对角线)

下面的代码的复杂度是多少?我认为时间复杂度将是O(row * cols)和恒定空间O(1)。 请提供想法。

function validateMatrixCoordinates(arrayMatrix, x, y) {
  if (!Array.isArray(arrayMatrix) || !Array.isArray(arrayMatrix[0])) {
    console.log("arrayMatrix is not a matrix of arrays");
    return false;
  }
  if (!Number.isInteger(x) || !Number.isInteger(y)) {
    console.log("Index is not an Integer");
    return false;
  }
  if (x < 0 || y < 0 || x > arrayMatrix.length - 1 || y > arrayMatrix[0].length - 1) {
    console.log("Index is Out Of Bounds");
    return false;
  }
  return true;
}

function sumMatrixNeighbors(arrayMatrix, x, y) {
  let rowLimit = arrayMatrix.length - 1;
  let columnLimit = arrayMatrix[0].length - 1;
  let sum = 0;

  if (!validateMatrixCoordinates(arrayMatrix, x, y)) {
    return;
  }
  for (let i = Math.max(0, x - 1); i <= Math.min(x + 1, rowLimit); i++) {
    for (let j = Math.max(0, y - 1); j <= Math.min(y + 1, columnLimit); j++) {
      if ((x !== i || y !== j) && Number.isInteger(arrayMatrix[i][j])) {
        sum += arrayMatrix[i][j];
      }
    }
  }

  return sum;
}

let input = [
  [0, 1, 2, 3, 4],
  [1, 2, 3, 4, 5],
  [2, 3, 4, 5, 6]
];

console.log('Result for [2, 1]: ' + sumMatrixNeighbors(input, 2, 1));
console.log('Result for [0, 0]: ' + sumMatrixNeighbors(input, 0, 0));
console.log('Result for ["a", 0]: ' + sumMatrixNeighbors(input, "a", 0));
console.log('Result for [1, -1]: ' + sumMatrixNeighbors(input, 1, -1));
console.log('Result for [1, 4]: ' + sumMatrixNeighbors(input, 1, 4));

0 个答案:

没有答案