0
votes

Hi I'm working on this little project which requires me to build a matrix in Java which resembles a chess board. I'm supposed to get the Knight to get from a point to another(In the way Knight moves). So I need to find the shortest way to get there in the end.

My problem is, I can't get to connect the edges to get to that point. I can find out if the vertex is a valid move but I can't seem to find a way to create nodes to get to that point. For Example,

0 XXXXX

1 XXXOX

2 XXXXX

3 XXKXX

4 XXXXX

5 XXXXX

I need to create nodes that connect K to O to find out shortest distance later. PS. I'll be okay with just hints of how to get there or just some tips. Don't really need the exact code. Thank you very much! I know it's a bad representation of matrix up there but spare me the critique please

2

2 Answers

0
votes

A classic Breadth-First-Search is probably the simplest approach:

class Location {
    int x;
    int y;

    List<Location> adjacent() {
        // TODO return list of locations reachable in a single step
    }
}

List<Location> findShortestPath(Location start, Location destination) {
    Location[][] previous = new Location[8][8];

    Deque<Location> queue = new ArrayDeque<>();
    queue.add(start);
    do {
        Location loc = queue.poll();
        for (Location n : loc.neighbors()) {
            if (previous[n.x][n.y] == null) {
                previous[n.x][n.y] = loc;
                queue.add(n);

                if (n.x == destination.x && n.y == destination.y) {
                    // we've found a way, let's reconstruct the list of steps
                    List<Location> path = new ArrayList<>();
                    for (Location l = n; l != start; l = previous[l.x][l.y]) {
                        path.add(l);
                    }
                    path.reverse();
                    return path;
                }
            }
        }
    } while (!queue.isEmpty());
    return null; // no path exists
}

This code enumerates all paths from the start location. Therefore, if there is a path to destination, it will find it. In addition, because paths are enumerated in order or ascending length, the first such path will be a shortest one.

0
votes

The chess board can be implemented by a 2d array. Each cell in the matrix can be considered to be a node (or vertex) in the graph. Edge is composed of two nodes (in this case two cells) one being the from or source [ lets call it Nod A] and other being the to or neighbor or destination node [ Lets call it node B].

Edge exits if there is a possibility of moving from node A to node B.

You can use Dijkstra's algorithm. http://krishnalearnings.blogspot.in/2015/07/implementation-in-java-for-dijkstras.html

For Node with the Knight's position you can see the possibilities of the cells where Knight can move to and add in the Min Heap. The weight of each edge is constant. You just need to update the cost of the Node.