Задача с 8 головоломками, используя лучший первый поиск в Java, выполняя бесконечно

Это класс Node.java, в котором я сохранил доску 3x3 и выполнил такие операции, как создание дочерних узлов, добавление новых дочерних элементов и вычисление значения эвристики. Этот Node Object используется Solver.java для решения 8-головоломок. Он имеет функции вроде перемещения вверх, вниз, влево, вправо, которые генерируют наследников, основываясь на возможности перемещения для 0.

public class Node {

    public int[][] board;
    public Node parent;
    public List<Node> childs;
    boolean isvisited = false;

    int heuristic;
    int hn;

    public void setvisited() {
        isvisited = true;
    }

    public boolean getvisited() {
        return isvisited;
    }

    Node(int[][] a) {
        board = new int[3][3];
        board = a;
        childs = new ArrayList<>();
    }

    @Override
    public String toString() {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board.length; j++) {
                System.out.print(board[i][j] + " |");
            }
            System.out.println();
        }

        System.out.println(heuristic + "||");
        return "";
    }

    public boolean checkSolution(int solution[][]) {

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board.length; j++) {
                if (board[i][j] != solution[i][j]) {
                    return false;
                }
            }

        }
        return true;
    }

    public int[] getQueenIndex() {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board.length; j++) {
                if (board[i][j] == 0) {

                    int a[] = {i, j};
                    return a;
                }
            }
            System.out.println();
        }
        return null;
    }

    public void moveup() {

        int[] index = getQueenIndex();
        int row = index[0];
        int column = index[1];
        if ((row == 0 && column == 0) || (row == 0 && column == 1) || (row == 0 && column == 2)) {
            return;
        } else {
            System.out.println("POssible U");
            int val1 = board[row][column];
            int val2 = board[row - 1][column];
            int arr[][] = new int[3][3];
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {

                    arr[i][j] = board[i][j];
                }
            }
            arr[row][column] = val2;
            arr[row - 1][column] = val1;

            Node node = new Node(arr);
            node.calculateHeuristic();
            childs.add(node);
        }
    }

    public void movedown() {
        int[] index = getQueenIndex();
        int row = index[0];
        int column = index[1];
        if ((row == 2 && column == 0) || (row == 2 && column == 1) || (row == 2 && column == 2)) {
            return;
        } else {
            System.out.println("POssible D");
            int val1 = board[row][column];
            int val2 = board[row + 1][column];

            int arr[][] = new int[3][3];
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {

                    arr[i][j] = board[i][j];
                }
            }
            arr[row][column] = val2;
            arr[row + 1][column] = val1;

            Node node = new Node(arr);
            node.calculateHeuristic();
            childs.add(node);
        }
    }

    public void moveright() {
        int[] index = getQueenIndex();
        int row = index[0];
        int column = index[1];
        if ((row == 0 && column == 2) || (row == 1 && column == 2) || (row == 2 && column == 2)) {
            return;
        } else {
            System.out.println("POssible R");
            int val1 = board[row][column];
            int val2 = board[row][column + 1];

            int arr[][] = new int[3][3];
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {

                    arr[i][j] = board[i][j];
                }
            }
            arr[row][column] = val2;
            arr[row][column + 1] = val1;

            Node node = new Node(arr);
            node.calculateHeuristic();
            childs.add(node);
        }
    }

    public void moveleft() {
        int[] index = getQueenIndex();
        int row = index[0];
        int column = index[1];
        if ((row == 0 && column == 0) || (row == 1 && column == 0) || (row == 2 && column == 0)) {
            return;
        } else {
            System.out.println("POssible L");
            int val1 = board[row][column];
            int val2 = board[row][column - 1];

            int arr[][] = new int[3][3];
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {

                    arr[i][j] = board[i][j];
                }
            }
            arr[row][column] = val2;
            arr[row][column - 1] = val1;

            Node node = new Node(arr);
            node.calculateHeuristic();
            childs.add(node);
        }
    }

    public void calculateHeuristic() {
        heuristic = 0;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[i][j] != 0) {


                    if (board[i][j] != Solver.solution[i][j]) {
                        heuristic += 1;
                        System.out.println(heuristic);
                    }
                }
            }
        }

    }

    public void addChild(Node e) {
        childs.add(e);
    }

    public List<Node> getChilds() {
        return childs;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Node node = (Node) o;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {

                if (this.board[i][j] != ((Node) o).board[i][j])
                    return false;
            }
        }
        return true;
    }

    @Override
    public int hashCode() {
        return Objects.hash(board);
    }
}

Solver.java Содержит основной код движка, который запускает алгоритм Best First Search в методе решения.

public class Solver {

    public static int[][] solution = {{1, 2, 3},
                                      {4, 5, 6},
                                      {7, 0, 8}};
    List<Node> closed = new ArrayList<>();
    PriorityQueue<Node> open;
    boolean isSolved = false;

    Solver() {
        open = new PriorityQueue<>(new Comparator<Node>() {
            @Override
            public int compare(Node o1, Node o2) {
                if (o1.heuristic > o2.heuristic) {
                    return 1;
                } else if (o1.heuristic < o2.heuristic) {
                    return -1;
                }
                return 0;
            }
        });
    }

    public boolean compareSolution(Node node) {
        if (node.heuristic == 0) return true;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (node.board[i][j] != solution[i][j]) {
                    return false;
                }
            }
        }

        return true;
    }

    private boolean isDuplicate(Node e) {
        boolean result = true;

        System.out.println(closed.contains(e));
        for (Node v : closed) {
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {
                    if (v.board[i][j] != e.board[i][j]) {
                        //   System.out.println("Not Duplicate!");
                        result = false;
                    }
                }
            }
        }
        //  System.out.println("Duplicate!");
        System.out.println("-----------------------");
        return result;
    }

    public void Solution(Node root) {
        open.add(root);

        while (!open.isEmpty() && !isSolved) {

            Node vertex = open.poll();
            vertex.isvisited = true;
            closed.add(vertex);
            System.out.println(vertex);
            //vertex.printBoard();
            if (!compareSolution(vertex)) {
                System.out.println("Run");
                vertex.moveup();
                vertex.movedown();
                vertex.moveleft();
                vertex.moveright();
                List<Node> list = vertex.getChilds();
                for (Node v : list) {
                    if (v.isvisited && isDuplicate(v)) {

                        System.out.println("Duplicate");
                        v.isvisited = true;

                    } else {
                        if (compareSolution(v)) {
                            System.out.println("zolution");
                            System.out.println("lll" + v);
                            isSolved = true;
                            break;
                        }
                        if (!isSolved) {
                            // v.calculateHeuristic();
                            System.out.println("------------------");
                            System.out.println(v);
                            System.out.println("------------------");
                            System.out.println("Priority:");
                            for (Node p : open
                            ) {
                                System.out.println(p);
                            }
                            System.out.println("------------------");
                            open.add(v);

                        } else {
                            System.out.println("Solution Found!");
                        }
                    }


                }
            }

        }
    }
}

Класс водителя Содержит основную функцию

public class DriverClass {
    public static void main(String args[]){
        int[][] problem={{2,3,1},
              {4,5,6},
              {7,8,0}};
         Node root=new Node(problem);
         root.calculateHeuristic();
         Solver solver=new Solver();

         solver.Solution(root);

     }
}

0 ответов

Другие вопросы по тегам