当前位置: 首页 > news >正文

JAVA学习-练习试用Java实现“深度优先搜索(DFS):实现八数码问题的解法(最短路径搜索)”

问题:

       java语言编辑,深度优先搜索(DFS):实现八数码问题的解法(最短路径搜索)。

解答思路:

       为了实现八数码问题的解法,我们可以使用深度优先搜索(DFS)结合回溯算法。以下是一个Java实现,它使用递归来实现DFS,并尝试找到从初始状态到目标状态的解。

import java.util.*;class State {int[] board;int moves;State parent;int cost; // g(n)public State(int[] board, int moves, State parent, int cost) {this.board = board.clone();this.moves = moves;this.parent = parent;this.cost = cost;}// Generate all possible states from the current statepublic List<State> generateNextStates() {List<State> nextStates = new ArrayList<>();int zeroIndex = findZeroIndex();int[] directions = {-1, 1, -3, 3}; // Up, Down, Left, Rightfor (int direction : directions) {int nextIndex = zeroIndex + direction;if (nextIndex >= 0 && nextIndex < 9 && isValidMove(zeroIndex, nextIndex)) {int[] newBoard = board.clone();swap(newBoard, zeroIndex, nextIndex);nextStates.add(new State(newBoard, moves + 1, this, cost + 1));}}return nextStates;}// Find the index of the zero in the boardprivate int findZeroIndex() {for (int i = 0; i < board.length; i++) {if (board[i] == 0) {return i;}}return -1;}// Check if the move is validprivate boolean isValidMove(int fromIndex, int toIndex) {return Math.abs(fromIndex % 3 - toIndex % 3) + Math.abs(fromIndex / 3 - toIndex / 3) == 1;}// Swap two elements in the arrayprivate void swap(int[] array, int i, int j) {int temp = array[i];array[i] = array[j];array[j] = temp;}// Check if the current state is the goal statepublic boolean isGoalState(int[] goal) {for (int i = 0; i < board.length; i++) {if (board[i] != goal[i]) {return false;}}return true;}}public class EightPuzzleSolver {private static final int[] GOAL_STATE = {1, 2, 3, 4, 5, 6, 7, 8, 0};private Set<Integer> visited;public List<int[]> solve(int[] initialBoard) {visited = new HashSet<>();State start = new State(initialBoard, 0, null, 0);return dfs(start);}private List<int[]> dfs(State current) {if (visited.contains(Arrays.hashCode(current.board))) {return null;}visited.add(Arrays.hashCode(current.board));if (current.isGoalState(GOAL_STATE)) {List<int[]> path = new ArrayList<>();while (current != null) {path.add(current.board.clone());current = current.parent;}Collections.reverse(path);return path;}for (State nextState : current.generateNextStates()) {List<int[]> result = dfs(nextState);if (result != null) {return result;}}return null;}public static void main(String[] args) {int[] initialBoard = {1, 2, 3, 4, 5, 6, 7, 8, 0};EightPuzzleSolver solver = new EightPuzzleSolver();List<int[]> solution = solver.solve(initialBoard);if (solution != null) {System.out.println("Solution found:");for (int[] state : solution) {for (int num : state) {System.out.print(num + " ");}System.out.println();}} else {System.out.println("No solution found.");}}}

       这段代码定义了一个'State'类来表示八数码问题的一个状态,包括棋盘布局、移动次数、父状态和路径成本。'EightPuzzleSolver'类实现了深度优先搜索算法,并从初始状态开始搜索解。如果找到解,它会返回一个包含从初始状态到目标状态的路径的列表。'main'方法提供了一个示例初始状态,并调用'solve'方法来找到解决方案。

(文章为作者在学习java过程中的一些个人体会总结和借鉴,如有不当、错误的地方,请各位大佬批评指正,定当努力改正,如有侵权请联系作者删帖。)

http://www.lryc.cn/news/600692.html

相关文章:

  • LangChain4j低阶+高阶Api+日志配置+监听器+重试机制+超时机制
  • 【LeetCode 热题 100】131. 分割回文串——回溯
  • 算法竞赛阶段二-数据结构(35)数据结构单链表模拟实现
  • Android-广播详解
  • golang实现一个定时引擎,功能包括按照corntab的时间任务实时增加、修改、删除定时任务
  • 常见sql深入优化( 二)
  • 一文学会c++list
  • 激光雷达-相机标定工具:支持普通相机和鱼眼相机的交互式标定
  • 二叉搜索树(Binary Search Tree)详解与java实现
  • Linux 如何统计系统上各个用户登录(或者登出)记录出现的次数?
  • Android-三种持久化方式详解
  • 摘录-打造第二大脑
  • J2EE模式---表现层集成模式
  • C++ TAP(基于任务的异步编程模式)
  • Web后端进阶:springboot原理(面试多问)
  • React入门学习——指北指南(第五节)
  • JavaScript手录06-函数
  • 【RK3568 PWM 子系统(SG90)驱动开发详解】
  • 数据赋能(336)——技术平台——智能化运营
  • Java动态调试技术原理
  • 【RocketMQ】一分钟了解RocketMQ
  • 告别复杂配置!Spring Boot优雅集成百度OCR的终极方案
  • Windows 平台源码部署 Dify教程(不依赖 Docker)
  • 《C++ list 完全指南:从基础到高效使用》
  • Linux——线程同步
  • InvokeRepeating避免嵌套调用
  • C++编程学习(第16天)
  • 7月26日京东秋招第一场第一题
  • 【第二章-数据的表示和运算】
  • 基于java的在线教育平台管理系统、在线学习系统的设计与实现