Search code examples
algorithmpuzzle

6*6 puzzle algorithm


I have a 6*6 puzzle with 35 numbers(1~35) in a random sequence. Use the blank one as a 'register' and move the numbers one by one to let them be in order. I can deal with a 3*3 puzzle, but how to deal with a 6*6 one? Could you give me some hints? enter image description here


Solution

  • The idea is the same, represent the problem as a states graph, and run shortest path algorithm.

    If the efficiency of the algorithm is important, you might want an informed algorithm -such as A* algorithm, which is expected to be pretty fast (relative to the alternatives) with a good admissible heuristic function.
    A slower though simpler solution can be running a BFS.

    Both algorithms (A*, BFS) are both complete (always finds a solutuion, if one exists) and optimal (finds shortest path).

    Also note, you can use macros to learn "good" series of moves, to get the algorithm faster. Ignore this improvement until you implement a working (though slow) solution.


    EDIT: Coding guidelines:
    Look at the problem as a graph: The graph will be G=(V,E) where V = { all possible states} and E = { (u,v) | can move from state u to state v within a single step }

    Now, with this graph - you have a starting position (the source, which is given as input) and a target (a sorted puzzle). Start a BFS or A* (have a look at the pseudo code of these in the attached wikipedia links), to find a path from the source to the destination. You should start with BFS - it is simpler.
    The path returned by the shortest path algorithm is identical to the series of moves you will have to do in order to get from the starting board to the target.

    Note: You do not need to create the actual graph! you just need a to hold the starting node (source) - and create its vertex, and have a successors:V->2^V function, that gives you the successors for each vertex (formally: successors(v) = { (v,u) | (v,u) is in E } ). This way, you can build the relevant part of the graph on the fly.