Bomb dropping algorithm

后端 未结 30 1273
挽巷
挽巷 2021-01-29 16:55

I have an n x m matrix consisting of non-negative integers. For example:

2 3 4 7 1
1 5 2 6 2
4 3 4 2 1
2 1 2 4 1
3 1 3 4 1
2 1 4 3 2
6 9 1 6 4
         


        
30条回答
  •  耶瑟儿~
    2021-01-29 17:36

    This can be solved using a tree of depth O(3^(n)). Where n is the sum of all of the squares.

    First consider that it is trivial to solve the problem with a tree of O(9^n), simply consider all of the possible bombing locations. For an example see Alfe's implementation.

    Next realize that we can work to bomb from the bottom up and still get a minimum bombing pattern.

    1. Start from the bottom left corner.
    2. Bomb it to oblivion with the only plays that make sense (up and to the right).
    3. Move one square to the right.
    4. While the target has a value greater than zero, consider each of the 2 plays that make sense (straight up or up and to the right), reduce the value of the target by one, and make a new branch for each possibility.
    5. Move another to the right.
    6. While the target has a value greater than zero, consider each of the 3 plays that make sense (up left, up, and up right), reduce the value of the target by one, and make a new branch for each possibility.
    7. Repeat steps 5 and 6 until the row is eliminated.
    8. Move up a row and repeat steps 1 to 7 until the puzzle is solved.

    This algorithm is correct because

    1. It is necessary to complete each row at some point.
    2. Completing a row always requires a play either one above, one below, or within that row.
    3. It is always as good or better to choose a play one above the lowest uncleared row than a play on the row or below the row.

    In practice this algorithm will regularly do better than its theoretical maximum because it will regularly bomb out neighbors and reduce the size of the search. If we assume that each bombing decreases the value of 4 additional targets, then our algorithm will run in O(3^(n/4)) or approximately O(1.3^n).

    Because this algorithm is still exponential, it would be wise to limit the depth of the search. We might limit the number of branches allowed to some number, X, and once we are this deep we force the algorithm to choose the best path it has identified so far (the one that has the minimum total board sum in one of its terminal leaves). Then our algorithm is guaranteed to run in O(3^X) time, but it is not guaranteed to get the correct answer. However, we can always increase X and test empirically if the trade off between increased computation and better answers is worthwhile.

提交回复
热议问题