1

此代码可视化 A* 算法。当它到达算法的末尾时,它会弹出一个警报,说明使用找到的路径

JOptionPane.showMessageDialog(null, "Path Found")

单击离开后,窗口消失,但随后在左上角再次呈现,没有关闭它的选项。此外,目标的路径是在单击离开后呈现的,但是在代码中它会在警报出现之前呈现。我确信问题出在这个方法上,特别是在我绘制或调用重绘方法的方式上,而不是实际算法本身。有人可以解释一下我哪里出了问题吗?

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    this.renderGrid(g);
    this.renderCloseCells(g);
    this.renderOpenCells(g);
    if (aStar.getOpenSet().size() > 0) {
        int lowestCostIndex = 0;
        for (int i = 0; i < aStar.getOpenSet().size(); i++){
            if (aStar.getOpenSet().get(i).getF() < aStar.getOpenSet().get(lowestCostIndex).getF()){
                lowestCostIndex = i;
            }
        }
        Cell current = aStar.getOpenSet().get(lowestCostIndex);
        if (aStar.getOpenSet().get(lowestCostIndex) == aStar.getEnd()){
            Cell temp = current;
            aStar.addItemPath(temp);
            while (temp.getParent() != null){
                aStar.addItemPath(temp.getParent());
                temp = temp.getParent();
            }
            System.out.println("Done");
            this.renderPath(g);
            JOptionPane.showMessageDialog(null, "Path Found");
            return;
        }
        aStar.removeCellOpenSet(current);
        aStar.addCellCloseSet(current);

        for (int i = 0; i < current.getNeighbors().size(); i++){
            Cell neighbor = current.getNeighbors().get(i);
            if (!aStar.getCloseSet().contains(neighbor)){
                int tempG = current.getG() + 1;
                if (aStar.getOpenSet().contains(neighbor)) {
                    if(tempG < neighbor.getG()){
                        neighbor.setG(tempG);
                    }
                } else {
                    neighbor.setG(tempG);
                    aStar.addCellOpenSet(neighbor);
                }
                neighbor.setH(aStar.heuristic(neighbor, aStar.getEnd()));
                neighbor.setF(neighbor.getG() + neighbor.getH());
                neighbor.setParent(current);
            }
        }

    } else {
        JOptionPane.showMessageDialog(null, "Path Not Found!");
    }
    this.repaint();
}

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

4

0 回答 0