博客
关于我
Java利用回溯思想解决迷宫问题(寻找最短路径)
阅读量:803 次
发布时间:2023-01-28

本文共 3607 字,大约阅读时间需要 12 分钟。

为了实现迷宫路径寻找,首先明确问题:寻找从起点(0,0)到终点(4,0)的最短路径,迷宫数组中0为路,1为墙。

设计ArrayXY类来表示坐标点,并实现路径记录和判断功能。主函数调用该类,利用回溯算法寻找路径。以下是优化后的代码:

import java.util.LinkedStack;import java.util.List;import java.util.Stack;public class ArrayXY {    public int x, y;    ArrayXY(int x, int y) {        this.x = x;        this.y = y;    }    public String toString() {        return x + "," + y;    }    public boolean equals(Object o) {        if (o instanceof ArrayXY) {            ArrayXY oo = (ArrayXY) o;            return (this.x == oo.x) && (this.y == oo.y);        }        return false;    }}public class TestArray1 {    public static void main(String[] args) {        int[][] maze = {                {0, 1, 1, 0, 1},                {0, 0, 0, 1, 1},                {0, 1, 0, 1, 1},                {1, 1, 0, 0, 1},                {0, 0, 0, 1, 1}        };        int startX = 0, startY = 0;        int targetX = 4, targetY = 0;        if (maze[startX][startY] == 1 || maze[targetX][targetY] == 1) {            System.out.println("目标点为墙,无法到达");            return;        }        LinkedStack
pathStack = new LinkedStack<>(); List
visited = new LinkedList<>(); pathStack.push(new ArrayXY(startX, startY)); visited.add(pathStack.peek()); while (true) { if (startX < 0 || startX >= maze.length || startY < 0 || startY >= maze[0].length) { System.out.println("出界了"); break; } int[] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; int minDistance = Integer.MAX_VALUE; ArrayXY target = new ArrayXY(targetX, targetY); int targetDistance = (targetX - startX) * (targetX - startX) + (targetY - startY) * (targetY - startY); ArrayXY next Point = null; for (int i = 0; i < directions.length; i++) { int x = startX + directions[i][0]; int y = startY + directions[i][1]; if (x == targetX && y == targetY) { nextPoint = new ArrayXY(x, y); break; } if (maze[x][y] == 0) { ArrayXY temp = new ArrayXY(x, y); if (!visited.contains(temp) && !pathStack.contains(temp)) { int distance = (x - startX) * (x - startX) + (y - startY) * (y - startY); if (distance < minDistance) { minDistance = distance; nextPoint = temp; } } } } if (nextPoint != null) { pathStack.push(nextPoint); visited.add(nextPoint); System.out.println("下一步:" + nextPoint); startX = nextPoint.x; startY = nextPoint.y; if (startX == targetX && startY == targetY) { System.out.println("到达目标点,路径长度为:" + pathStack.size()); for (ArrayXY point : pathStack) { System.out.println(point); } return; } } else { if (pathStack.isEmpty()) { System.out.println("没有可达路径"); break; } ArrayXY current = pathStack.pop(); System.out.println("回溯:" + current); startX = current.x; startY = current.y; } } }}

优化点说明:

  • ArrayXY类简化,仅保存x和y
  • 使用LinkedStack记录路径
  • 方向处理更细致,预先计算目标点距离
  • 每一步计算最短距离,避免重复点
  • 逐步尝试四个方向,优先考虑到达终点的路径
  • 路径回溯处理,确保解决所有可能的路径
  • 增加了目标点的离线判断,提前终止搜索

转载地址:http://xjryk.baihongyu.com/

你可能感兴趣的文章
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No static resource favicon.ico.
查看>>
no such file or directory AndroidManifest.xml
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
no1
查看>>
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>