常用的启发式算法:写一个八数码问题的启发式搜索的java代码

编写八数码问题的启发式搜索的Java代码。以下是一个示例代码:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.PriorityQueue;

public class EightPuzzle {
    private static final int[][] GOAL_STATE = {{1, 2, 3}, {4, 5, 6}, {7, 8, 0}};

    private static int[][] initialState = {{5, 1, 3}, {4, 0, 2}, {7, 8, 6}};

    public static void main(String[] args) {
        PriorityQueue<Node> openList = new PriorityQueue<>((a, b) -> (a.f - b.f));
        HashSet<Node> closedList = new HashSet<>();

        Node startNode = new Node(initialState, 0, 0);
        openList.add(startNode);

        while (!openList.isEmpty()) {
            Node currentNode = openList.poll();
            closedList.add(currentNode);

            if (isGoalState(currentNode.state)) {
                System.out.println("Goal state reached!");
                printPath(currentNode);
                return;
            }

            ArrayList<Node> neighbors = generateNeighbors(currentNode);
            for (Node neighbor : neighbors) {
                if (closedList.contains(neighbor)) {
                    continue;
                }

                int g = currentNode.g + 1;
                int h = calculateHeuristic(neighbor.state);
                int f = g + h;

                if (openList.contains(neighbor)) {
                    Node existingNode = getNodeFromOpenList(neighbor, openList);
                    if (existingNode.f <= f) {
                        continue;
                    }
                    openList.remove(existingNode);
                }

                neighbor.g = g;
                neighbor.h = h;
                neighbor.f = f;
                neighbor.parent = currentNode;

                openList.add(neighbor);
            }
        }

        System.out.println("Goal state not reachable!");
    }

    private static boolean isGoalState(int[][] state) {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (state[i][j] != GOAL_STATE[i][j]) {
                    return false;
                }
            }
        }
        return true;
    }

    private static ArrayList<Node> generateNeighbors(Node node) {
        ArrayList<Node> neighbors = new ArrayList<>();
        int[][] state = node.state;
        int row = 0, col = 0;

        // Find the position of the blank tile
        outerloop:
        for (row = 0; row < 3; row++) {
            for (col = 0; col < 3; col++) {
                if (state[row][col] == 0) {
                    break outerloop;
                }
            }
        }

        // Generate neighbors by moving the blank tile
        // Up
        if (row > 0) {
            int[][] newState = cloneState(state);
            swap(newState, row, col, row - 1, col);
            neighbors.add(new Node(newState, 0, 0));
        }

        // Down
        if (row < 2) {
            int[][] newState = cloneState(state);
            swap(newState, row, col, row + 1, col);
            neighbors.add(new Node(newState, 0, 0));
        }

        // Left
        if (col > 0) {
            int[][] newState = cloneState(state);
            swap(newState, row, col, row, col - 1);
            neighbors.add(new Node(newState, 0, 0));
        }

        // Right
        if (col < 2) {
            int[][] newState = cloneState(state);
            swap(newState, row, col, row, col + 1);
            neighbors.add(new Node(newState, 0, 0));
        }

        return neighbors;
    }

    private static int[][] cloneState(int[][] state) {
        int[][] newState = new int[3][3];
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                newState[i][j] = state[i][j];
            }
        }
        return newState;
    }

    private static void swap(int[][] state, int i, int j, int x, int y) {
        int temp = state[i][j];
        state[i][j] = state[x][y];
        state[x][y] = temp;
    }

    private static int calculateHeuristic(int[][] state) {
        int heuristic = 0;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (state[i][j] != 0 && state[i][j] != GOAL_STATE[i][j]) {
                    heuristic++;
                }
            }
        }
        return heuristic;
    }

    private static Node getNodeFromOpenList(Node targetNode, PriorityQueue<Node> openList) {
        for (Node node : openList) {
            if (node.equals(targetNode)) {
                return node;
            }
        }
        return null;
    }

    private static void printPath(Node node) {
        if (node.parent != null) {
            printPath(node.parent);
        }
        printState(node.state);
        System.out.println();
    }

    private static void printState(int[][] state) {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(state[i][j] + " ");
            }
            System.out.println();
        }
    }

    static class Node {
        int[][] state;
        int g;
        int h;
        int f;
        Node parent;

        Node(int[][] state, int g, int h) {
            this.state = state;
            this.g = g;
            this.h = h;
            this.f = g + h;
            parent = null;
        }

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

        @Override
        public int hashCode() {
            int result = 0;
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {
                    result = result * 31 + state[i][j];
                }
            }
            return result;
        }
    }
}

请注意,此示例代码中使用的初始状态是{{5, 1, 3}, {4, 0, 2}, {7, 8, 6}},你可以根据需要进行更改。启发式函数使用的是错误放置的方块数量,如果你想使用其他启发式函数,可以在calculateHeuristic方法中修改。 此外,代码中还提供了一个printState方法来打印状态矩阵以及最终搜索路径的printPath方法。你可以根据需要进行修改和扩展。

希望这段代码能帮到你

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以回答这个问题。以下是一个八数码问题启发式搜索Java代码: ```java import java.util.*; public class EightPuzzle { private static final int[][] GOAL = {{1, 2, 3}, {4, 5, 6}, {7, 8, 0}}; private static final int[][] MOVES = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; private int[][] board; private int zeroRow; private int zeroCol; private int moves; public EightPuzzle(int[][] blocks) { board = new int[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { board[i][j] = blocks[i][j]; if (board[i][j] == 0) { zeroRow = i; zeroCol = j; } } } moves = 0; } public int manhattan() { int distance = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] != 0) { int row = (board[i][j] - 1) / 3; int col = (board[i][j] - 1) % 3; distance += Math.abs(row - i) + Math.abs(col - j); } } } return distance; } public boolean isGoal() { return Arrays.deepEquals(board, GOAL); } public Iterable<EightPuzzle> neighbors() { List<EightPuzzle> list = new ArrayList<>(); for (int[] move : MOVES) { int newRow = zeroRow + move[0]; int newCol = zeroCol + move[1]; if (newRow >= 0 && newRow < 3 && newCol >= 0 && newCol < 3) { int[][] newBoard = new int[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { newBoard[i][j] = board[i][j]; } } newBoard[zeroRow][zeroCol] = newBoard[newRow][newCol]; newBoard[newRow][newCol] = 0; EightPuzzle neighbor = new EightPuzzle(newBoard); neighbor.moves = moves + 1; list.add(neighbor); } } return list; } public int getMoves() { return moves; } public static void main(String[] args) { int[][] blocks = {{1, 2, 3}, {4, 5, 6}, {7, 0, 8}}; EightPuzzle puzzle = new EightPuzzle(blocks); System.out.println(puzzle.manhattan()); System.out.println(puzzle.isGoal()); for (EightPuzzle neighbor : puzzle.neighbors()) { System.out.println(neighbor.manhattan()); System.out.println(neighbor.isGoal()); } } } ``` 这个代码实现了一个八数码问题启发式搜索,其中使用了曼哈顿距离作为启发函数。在`main`方法中,我们可以看到如何使用这个类来计算曼哈顿距离、判断是否到达目标状态以及获取邻居状态。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值