这是什么最短路径迷宫算法?

3

我正在尝试了解和理解尽可能多的算法,在一份比赛资料包中偶然发现了一个奇怪的算法,它可以找到解决迷宫(即最短路径)所需的最小步数。虽然我已经完全理解了它,但我不知道这是什么算法,而且这个资料包没有说明它的名称。我真的想知道这个算法的名称(如果有的话),以便我可以进行更多的研究。

import java.io.File;
import java.util.Scanner;

class spot {

    char type;
    int distance;
    spot closest;

    public spot() {
        type = '.';
        distance = Integer.MAX_VALUE;
        closest = null;
    }
}

public class myalg {

    public static void main(String args[]) throws Exception {
        int moves = 0;

        Scanner keyb = new Scanner(new File("src/mar2014/maze2.txt"));

        int rows = keyb.nextInt();
        int cols = keyb.nextInt();
        spot mat[][] = new spot[rows][cols];
        keyb.nextLine();
        spot startSpot = null;
        spot endSpot = null;    
        for (int i = 0; i < mat.length; i++) {
            String line = keyb.nextLine();
            for (int j = 0; j < mat[i].length; j++) {
                mat[i][j] = new spot();
                mat[i][j].type = line.charAt(j);
                if (mat[i][j].type == 'S') {
                    startSpot = mat[i][j];
                    startSpot.distance = 0;
                    startSpot.type = ' ';
                }
                if (mat[i][j].type == 'E') {
                    endSpot = mat[i][j];
                    endSpot.type = ' ';
                }
            }
        }

        boolean changeMade = true;
        while (changeMade) {
            changeMade = false;
            for (int i = 0; i < mat.length; i++) {
                for (int j = 0; j < mat[i].length; j++) {
                    spot thisSpot = mat[i][j];
                    spot adjacentSpots[] = {null, null, null, null};
                    if (i > 0) {
                        adjacentSpots[0] = mat[i - 1][j];
                    }
                    if (i < cols - 1) {
                        adjacentSpots[1] = mat[i + 1][j];
                    }
                    if (j > 0) {
                        adjacentSpots[2] = mat[i][j - 1];
                    }
                    if (j < rows - 1) {
                        adjacentSpots[3] = mat[i][j + 1];
                    }
                    if (thisSpot.type == ' ') {
                        for (int k = 0; k < 4; k++) {
                            if (adjacentSpots[k] != null && adjacentSpots[k].distance < (thisSpot.distance - 1)) {
                                thisSpot.distance = adjacentSpots[k].distance + 1;
                                thisSpot.closest = adjacentSpots[k];
                                changeMade = true;
                            }
                        }
                    }
                }
            }
        }

        spot spot = endSpot;
        while(spot != startSpot) {
            moves++;
            spot.type = '.';
            spot = spot.closest;
        }

        System.out.println(moves);
    }
}
1个回答

3
广度优先搜索与回溯。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接