js皇后棋算法-生成器方法/传统递归两种方法

function conflict(state, nextX) {
  let nextY = state.length;
  for (let i = 0; i < nextY; i++) {
    if ([0, nextY - i].indexOf(Math.abs(state[i] - nextX)) > -1) {
      return true;
    }
  }
  return false;
}
//------------------------------------生成器------------------------
/**
 * 大致解析(错了勿喷):下面有两个yield,但是,当state的长度小于8时,yield都会被内部消化,只有最后一次[i.concat(res)]的时候才会被yield到外部
 */
function* queens(num = 8, state = []) {
  for (let i = 0; i < num; i++) {
    if (!conflict(state, i)) {
      if (state.length == num - 1) {
        yield i;
      } else {
        for (let res of queens(num, state.concat([i]))) {
          yield [i].concat(res);
        }
      }
    }
  }
}
var a = queens();
let num = 0;
for (let j of a) {
  console.log(j);
  num++;
}
console.log(num);


//------------------------------------------递归--------
/**
 * 用递归和闭包重新写
 */
function queens1(num = 8, state = []) {
  let all = [];
  function inner(num, state) {
    for (let i = 0; i < num; i++) {
      if (!conflict(state, i)) {
        let istate = state.concat([i]);
        if (istate.length == 8) {
          all.push(istate);
        } else {
          inner(num, istate);
        }
      }
    }
  }
  inner(num, state);
  return all;
}

console.log(queens1());

生成器的方法是借鉴的python某大佬写的改来的,但是yield具体没有全部打印出来的原因没太搞懂

posted @ 2022-03-23 15:12  xiaochuchun  阅读(96)  评论(0编辑  收藏  举报