【问题标题】:Algorithm: Generate path for a Knight move to all Chess Board Squares算法:为骑士移动到所有棋盘格生成路径
【发布时间】:2021-01-16 17:33:09
【问题描述】:

问题描述

我正在尝试获得一种算法,该算法将找到骑士可以在棋盘中移动并访问所有方格而不重复任何方格的可能移动序列的路径。如下图所示,这是可能的

我的方法

为了尝试实现这一点,我已按照以下步骤操作

  1. allSquares ['a1', 'a2', 'a3', ..., 'h7', 'h8'] 创建了一个数组
  2. 创建了另一个visitedSquares 数组。最初这是空的[]
  3. 为每个正方形创建了一个paths 数组的函数。这表示骑士可以从其他方格移动到的方格
{
  "a8": ["c7", "b6"],
  "a7": ["c6", "b5","c8"],
  "a6": ["c5","b4","c7","b8"],

  ...
  "h3": ["f2","g1","f4","g5"],
  "h2": ["f1","f3","g4"],
  "h1": ["f2","g3"]
}
  1. 创建了一个getNextNode() 函数来返回访问节点的最大成本
  2. 最后我尝试通过以下步骤解决最长路径
    while (this.squaresNotVisited.length > 0) {
      const nextTerm = this.getNextNode();
      const currentCost = this.pathCosts[nextTerm[0]];
      const nextPaths: string[] = this.paths[nextTerm[0]];
      nextPaths.forEach(square => {
        if (this.pathCosts[square] < currentCost + 1) {
          this.pathCosts[square] = currentCost + 1;
        }
      });

      this.squaresVisited = [...this.squaresVisited, nextTerm[0]];
      this.squaresNotVisited = this.allSquares.filter(
        x => !this.squaresVisited.includes(x)
      );
    }

下面是完整的 Javascript 代码

class AppComponent {
  board = {
    columns: ["a", "b", "c", "d", "e", "f", "g", "h"],
    rows: [8, 7, 6, 5, 4, 3, 2, 1]
  };
  allSquares = this.board.columns.reduce(
    (prev, next) => [...prev, ...this.board.rows.map(x => next + x)],
    []
  );

  currentKnightPosition = "h5";
  squaresVisited = [];
  squaresNotVisited = [...this.allSquares];
  nextPossibleKnightPosition = currentKnightPosition => {
    const row = this.board.columns.indexOf(currentKnightPosition[0]);
    const column = Number(currentKnightPosition[1]) - 1;
    return [
      [column - 1, row - 2],
      [column - 1, row + 2],
      [column - 2, row - 1],
      [column - 2, row + 1],
      [column + 1, row - 2],
      [column + 1, row + 2],
      [column + 2, row - 1],
      [column + 2, row + 1]
    ]
      .filter(
        ([row, column]) => column >= 0 && column < 8 && row >= 0 && row < 8
      )
      .map(
        ([row, column]) =>
          this.board.columns[column] + this.board.rows[8 - row - 1]
      );
  };

  paths = this.allSquares.reduce(
    (prev, next) => ({
      ...prev,
      [next]: this.nextPossibleKnightPosition(next)
    }),
    {}
  );

  isNextSquare = square =>
    this.nextPossibleKnightPosition(this.currentKnightPosition).includes(
      square
    );
  costs = { [this.currentKnightPosition]: 0 };
  pathCosts = {
    ...this.allSquares.reduce(
      (prev, next) => ({ ...prev, [next]: -Infinity }),
      {}
    ),
    [this.currentKnightPosition]: 0
  };

  getNextTerm = () => {
    let nonVisted = Object.entries(this.pathCosts).filter(
      ([x, y]) => !this.squaresVisited.includes(x)
    );

    const maxPath = Math.max(...Object.values(nonVisted.map(([, x]) => x)));
    return nonVisted.find(([, x]) => x === maxPath);
  };
  costsCalc = () => {
    while (this.squaresNotVisited.length > 0) {
      const nextTerm = this.getNextTerm();
      const currentCost = this.pathCosts[nextTerm[0]];
      const nextPaths = this.paths[nextTerm[0]];
      nextPaths.forEach(square => {
        if (this.pathCosts[square] < currentCost + 1) {
          this.pathCosts[square] = currentCost + 1;
        }
      });

      this.squaresVisited = [...this.squaresVisited, nextTerm[0]];
      this.squaresNotVisited = this.allSquares.filter(
        x => !this.squaresVisited.includes(x)
      );
    }
  };

  ngOnInit() {
     this.costsCalc();
      console.log(Math.max(...Object.values(this.pathCosts)))
    
  }
}

const app = new AppComponent();
app.ngOnInit()

问题

该方法返回最长路径是 51 ......这是不正确的,因为正方形的数量是 64。我被困在错误是在我的代码中还是错误是在我使用的方法中。下面也是demo on stackblitz

【问题讨论】:

  • 这篇维基百科文章提到了一个简单的启发式(Warndorff 规则):en.wikipedia.org/wiki/Knight%27s_tour#Warnsdorff's_rule。如果您的棋盘尺寸是 8x8,那么您总能找到解决方案,我不确定更大的棋盘。您还可以查看此站点以获取更多伪代码:bradfieldcs.com/algos/graphs/knights-tour
  • 如果我这样做console.log(this.pathCosts) 然后我看到没有 1,2,3 等和其他多个,对吗?
  • @Surt 路径是一个对象{ "a8": [ "c7", "b6" ], "a7": [ "c6", "b5", "c8" ], "a6" : [ "c5", "b4", "c7", "b8" ],
  • 如果我在方格 a8,那么可用路径是 c7 和 b6,与 a7 相同。路径将是 c6、b5、c8...

标签: javascript algorithm


【解决方案1】:

你的功能卡住了

在每个步骤中,您的方法只采用最长的路径并更新其所有邻居。这不是撤销决定,这就是为什么它会卡在 52 的路径长度上。

当您发现您当前的解决方案不起作用时,您必须返回,即Backtracking

可能的实现

...使用Warnsdorff's rule

const findPath = (knightPosition) => {
  if (squaresVisited.size === allSquares.length - 1) return [knightPosition]

  squaresVisited.add(knightPosition)
  const neighbors = paths[knightPosition]
    .filter(neighbor => !squaresVisited.has(neighbor))
    .map(neighbor => {
      const neighborCount = paths[neighbor]
        .filter(square => !squaresVisited.has(square))
        .length
      return {
        position: neighbor,
        count: neighborCount
      }
    })
  const minNeighborsCount = Math.min(...neighbors.map(({ count }) => count))
  const minNeighbors = neighbors.filter(neighbor => neighbor.count === minNeighborsCount)
  for (const minNeighbor of minNeighbors) {
    const { position, count } = minNeighbor
    const path = findPath(position)
    if (path) return [knightPosition, ...path]
  }
  squaresVisited.delete(knightPosition)
}

完整的工作示例

const board = {
  columns: ["a", "b", "c", "d", "e", "f", "g", "h"],
  rows: [8, 7, 6, 5, 4, 3, 2, 1]
};

const allSquares = board.columns.reduce(
  (prev, next) => [...prev, ...board.rows.map(x => next + x)],
  []
);

const nextPossibleKnightPositions = currentKnightPosition => {
  const row = board.columns.indexOf(currentKnightPosition[0]);
  const column = Number(currentKnightPosition[1]) - 1;
  return [
    [column - 1, row - 2],
    [column - 1, row + 2],
    [column - 2, row - 1],
    [column - 2, row + 1],
    [column + 1, row - 2],
    [column + 1, row + 2],
    [column + 2, row - 1],
    [column + 2, row + 1]
  ]
    .filter(
      ([row, column]) => column >= 0 && column < 8 && row >= 0 && row < 8
    )
    .map(
      ([row, column]) =>
        board.columns[column] + board.rows[8 - row - 1]
    );
};

const paths = allSquares.reduce(
  (prev, next) => ({
    ...prev,
    [next]: nextPossibleKnightPositions(next)
  }),
  {}
);

const squaresVisited = new Set();

const findPath = (knightPosition) => {
  if (squaresVisited.size === allSquares.length - 1) return [knightPosition]

  squaresVisited.add(knightPosition)
  const neighbors = paths[knightPosition]
    .filter(neighbor => !squaresVisited.has(neighbor))
    .map(neighbor => {
      const neighborCount = paths[neighbor]
        .filter(square => !squaresVisited.has(square))
        .length
      return {
        position: neighbor,
        count: neighborCount
      }
    })
  const minNeighborsCount = Math.min(...neighbors.map(({ count }) => count))
  const minNeighbors = neighbors.filter(neighbor => neighbor.count === minNeighborsCount)
  for (const minNeighbor of minNeighbors) {
    const { position, count } = minNeighbor
    const path = findPath(position)
    if (path) return [knightPosition, ...path]
  }
  squaresVisited.delete(knightPosition)
}

const path = findPath("h5");
console.log(path)

allSquares.forEach(square => {
  squaresVisited.clear()
  const path = findPath(square)
  if(path.length !== 64) throw new Error(sqaure)
})
console.log("Works for all squares")

【讨论】:

  • 感谢您的回答,不幸的是,如果我尝试实现此功能,它会不断破坏我的应用程序
  • 你完全正确!这件事需要很长时间才能计算出来,因为仅靠回溯很难解决这个问题。您可以尝试通过使用更合适的数据结构或更有效地搜索来优化它(例如更早地修剪不可能的路径或使用上面 cmets 中提到的启发式方法:en.wikipedia.org/wiki/Knight%27s_tour#Warnsdorff's_rule
  • 我已更新答案以使用 Warnsdorff 规则。
猜你喜欢
  • 1970-01-01
  • 2021-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-23
  • 1970-01-01
  • 2017-03-20
  • 2017-05-03
相关资源
最近更新 更多