繁体   English   中英

在Java迷宫中使用DFS进行递归查找最短路径

[英]Recursive for find shortest path using DFS in maze in java

`使用此代码时出现堆栈溢出错误。 如果我们已经找到最短的路径,我希望它能正常工作,那么递归代码将停止。 迷宫包含字符“#”和“”。 如果我找到了最短的路径,则该路径将标记为“。” 请帮忙谢谢。

public static int getCoordinateY(String location){ //to get x coordinate
    String y = location.substring(2, 4);
    int coor = (y.charAt(0) - 'Q') * 10 + Character.getNumericValue(y.charAt(1));`enter code here`
    return coor;
    }
public boolean canPass(int y,int x) { //you can keep going if you not found # and .
    if(map[y][x] == '#' || map[y][x] == '.' ) {
        return false;
    }
    return true;
}
public Character[][] cloneArray(Character[][] src) { //copy array
    int length = src.length;
    Character[][] target = new Character[length][src[0].length];
    for (int i = 0; i < length; i++) {
        System.arraycopy(src[i], 0, target[i], 0, src[i].length);
    }
    return target;
}
public void finish(int x,int y){ //goal
    xgoal=x; 
    ygoal=y;
}
public int getDistance(){ //shortest distance from shortest path
    return finalDistance;
}
public void shortestPathStart(int xStart,int yStart, int xEnd, int yEnd){
    set('S',xStart,yStart); //start coordinate
    finish(xEnd,yEnd);
    shortestPathRec(xStart+1,yStart,0,map);//to right
    shortestPathRec(xStart-1,yStart,0,map);// to left
    shortestPathRec(xStart,yStart+1,0,map);//to up
    shortestPathRec(xStart,yStart-1,0,map);// to down
    map = result; //final map with '.'
    set('F',xEnd,yEnd);
    print();
}
public void shortestPathRec(int x,int y,int step,Character[][] map){
    if(canPass(x,y)){
        step++;
        Character[][] temp = cloneArray(map);
        temp[x][y] = '.'; //in the maze, '.' using for flags
        if(x == xgoal && y == ygoal){//if already found the goal
            hasDone = true;
            finalDistance = step;
            result = temp;
            return;
        }
        if(hasDone==true && finalDistance<step){ //if shortest path is found other path should be in this condition
            return;
        }
        shortestPathRec(x+1,y,step,temp);//calltherecursive again
        shortestPathRec(x-1,y,step,temp);
        shortestPathRec(x,y+1,step,temp);
        shortestPathRec(x,y-1,step,temp);
    }
}

问题分析

您无法防范物理回溯:移动到墙上,但是没有备份到调用堆栈中(撤消最后一步),而是转到下一个递归调用并执行相反的步骤-采取第二个无用的步骤最多备份0个无用的步骤。 您的代码将无限地在这两个正方形之间移动,直到超过堆栈限制。

修理

简化您的代码,以便您永远不会走到在此路径上已经访问过的广场。 这很容易进行在线研究。 Dijkstra的算法是最早的通用解决方案之一。

了解基本调试。 除其他外,在每个例程的入口和出口插入打印语句,打印输入参数和返回值。 为了更加清晰,请保持一个深度计数器并适当缩进打印件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM