简体   繁体   中英

Finding the shortest path in a maze

I am amateur programmer learning how to program. I have never had any computer science courses so I have hard times with this trivial problem:

class Room {
    String name;
    ArrayList<Room> neighbors = new ArrayList<Room>();

    // constructor with name
    // getters
    void addNeighbor(Room room) {
        neighbors.add(room);
    }
}

class Finder {
    void findShortestPath(Room start, Room end) {
        // ?
    }
}

Every room has some neighbors. More then 4, so it's not like matrix oriented problem. You are given end room and you must find shortest path from the start room (comparing the names of the rooms). Result should be "way" like:

Start: Kitchen

End: Toilet

Path: Kitchen, Living Room, Corridor, Bedroom, Toilet

I think I must use some recursion for the rooms and I think I should save where I have already been in some stack. But I don't really know how to start.

Can some of you CS guys help me? Thanks

You are looking for BFS .

In your case, the graph G = (V,E) is actually V= { all rooms } and E = {(u,v), (v,u) | u and v are neighboring rooms } E = {(u,v), (v,u) | u and v are neighboring rooms }

Note that you don't care you don't have all edges [neighbors] before the algorithm starts - you know how to calculate the relevant set of edges [and rooms] on the fly, using the neighbors field.
This is true since every "edge" you need to use for your path - was "discovered" when you discovered the room which is closer in the path to the source.

You can have a look at this post - how you can find the actual path after running a BFS.

You want to write a breadth-first search. There are many resources available on this topic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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