数独解算器陷入无限循环中,有些困惑

时间:2018-09-05 06:42:43

标签: javascript sudoku

我在遵循各种教程和我自己的知识的基础上构建了以下求解器,现在我想从Peter Norvig的拼图网站输入以下拼图,该拼图陷入无限循环,但可以解决更简单的问题。

行之有效的难题:

[
  [5,3,0,0,7,0,0,0,0],
  [6,0,0,1,9,5,0,0,0],
  [0,9,8,0,0,0,0,6,0],
  [8,0,0,0,6,0,0,0,3],
  [4,0,0,8,0,3,0,0,1],
  [7,0,0,0,2,0,0,0,6],
  [0,6,0,0,0,0,2,8,0],
  [0,0,0,4,1,9,0,0,5],
  [0,0,0,0,8,0,0,7,9]
]

陷入无限循环的难题:

[
  [4,0,0,0,0,0,8,0,5],
  [0,3,0,0,0,0,0,0,0],
  [0,0,0,7,0,0,0,0,0],
  [0,2,0,0,0,0,0,6,0],
  [0,0,0,0,8,0,4,0,0],
  [0,0,0,0,1,0,0,0,0],
  [0,0,0,6,0,3,0,7,0],
  [5,0,0,2,0,0,0,0,0],
  [1,0,4,0,0,0,0,0,0]
]

当然还有求解器:

sudokuSolver(puzzle) => {
  let nonPossibilities = {},
    impossibleNumbers, count = 81;
  while (count > 0) {
    count = 0;
    for (let v = 0; v < puzzle.length; v++) {
      for (let h = 0; h < puzzle.length; h++) {
        //if value is a empty or 0
        if (puzzle[v][h] === 0) {
          //reset
          nonPossibilities = {};
          //check the box
          for (let i = 0; i < 9; i++) {
            //first check vertically 
            if (puzzle[v][i] > 0) {
              nonPossibilities[puzzle[v][i]] = true;
            }
            //followed by horizontally 
            if (puzzle[i][h] > 0) {
              nonPossibilities[puzzle[i][h]] = true;
            }
          }

          for (let vertBox = Math.floor(v / 3) * 3; vertBox < Math.floor(v / 3) * 3 + 3; vertBox++) {
            for (let horiBox = Math.floor(h / 3) * 3; horiBox < Math.floor(h / 3) * 3 + 3; horiBox++) {
              if (puzzle[vertBox][horiBox]) {
                nonPossibilities[puzzle[vertBox][horiBox]] = true;
              }
            }
          }

          impossibleNumbers = Object.keys(nonPossibilities);
          if (impossibleNumbers.length === 8) {
            for (let ii = 1; ii < 10; ii++) {
              if (impossibleNumbers.indexOf(ii.toString()) < 0) {
                // console.log(vert,horz);
                puzzle[v][h] = ii;
              }
            }
          } else {
            count++;
          }
        }
      }
    }
  }
  return puzzle;
}

0 个答案:

没有答案