我在for循环中使用递归:

var matrix = [
    [0, 1, 1, 0, 0],
    [1, 0, 1, 1, 1],
    [1, 1, 0, 1, 0],
    [0, 1, 1, 0, 1],
    [0, 1, 0, 1, 0]
];
var startVertex = 1;
var vertices = [];
var lastTakenOff = -1;

var findHamilton = function (v) {
  for (var i = 0; i < matrix[v].length; i++) {
    if (matrix[v][i] === 1 && vertices.indexOf(i) === -1 && i > lastTakenOff &&
        vertices.length < matrix[v].length) {
      vertices.push(i);
      console.log(vertices)
      lastTakenOff = -1;
      return findHamilton(i);
    } else if (vertices.length < matrix[v].length) {
      console.log(vertices);
      lastTakenOff = vertices.pop();
      return findHamilton(vertices[vertices.length - 1]);
    }
  }
};

vertices.push(startVertex);
findHamilton(startVertex);
console.log(vertices)


经过3次迭代后,我得到了错误:for循环中的matrix [v]未定义。如果我还没有,那么一切都还好。如果还有其他方式,我该如何使用递归?

编辑:
我添加了所有代码

最佳答案

问题或其中之一是该句子return findHamilton(vertices[vertices.length - 1]); findHamilton正在等待一个int参数,但vertices[vertices.length - 1]可能是undefined
所以我不知道这是否会返回您等待的值,但是请尝试以下操作:

var matrix = [
    [0, 1, 1, 0, 0],
    [1, 0, 1, 1, 1],
    [1, 1, 0, 1, 0],
    [0, 1, 1, 0, 1],
    [0, 1, 0, 1, 0]
];
var startVertex = 1;
var vertices = [];
var lastTakenOff = -1;

var findHamilton = function (v) {

    for (var i = 0; i < matrix[v].length; i++) {

        if (matrix[v][i] === 1 && vertices.indexOf(i) === -1 && i > lastTakenOff &&
            vertices.length < matrix[v].length) {
            vertices.push(i);
            console.log(vertices)
            lastTakenOff = -1;
            return findHamilton(i);
        } else if (vertices[vertices.length - 1] && v < matrix.length && vertices.length < matrix[v].length) {
            console.log(vertices);
            lastTakenOff = vertices.pop();
            return findHamilton(vertices[vertices.length - 1]);
        }
    }
};


vertices.push(startVertex);
findHamilton(startVertex);
console.log(vertices)


我刚刚编辑了else if谓词

关于javascript - 在FOR循环中递归,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34343522/

10-12 16:40