Rush Hour - Solving the game

前端 未结 7 1832
太阳男子
太阳男子 2021-01-30 10:47

Rush Hour
if you\'re not familiar with it, the game consists of a collection of cars of varying sizes, set either horizontally or vertically, on a NxM grid

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 11:32

    You should recurse (your "backtracking" solution). This is probably the only way to solve puzzles like this; the question is how to do it fast.

    As you noted, the search space will be large - but not too large, if you have a reasonable sized board. For example, you've drawn a 6x6 grid with 12 cars on it. Assuming each is a size-2 car, that gives 5 spaces/per, so at most 5^12 = 244,140,625 potential positions. This even fits in a 32-bit integer. So one possibility is to allocate a huge array, one slot per potential position, and use memoization to make sure that you don't repeat a position.

    The next thing to note is that most of those "potential" positions aren't, in fact, possible (they'd involve cars overlapping). So instead, use a hash table to keep track of each position you've visited. This will have a small memory overhead per entry, but it'll probably be more space-efficient than the "huge array" solution. It will, however, take a bit longer for each entry access.

    As the MIT paper in @Daniel's answer says, the problem is PSPACE-complete, meaning many of the tricks used to reduce the complexity of NP problems probably can't be used.

    That said, either of the two above solutions to the repeated-position problem should work for smallish grids. It'll all be determined by how big the problem is, and how much memory your computer has; but the example you displayed should be no trouble at all, even for a ordinary desktop computer.

提交回复
热议问题