Bomb dropping algorithm

后端 未结 30 841
挽巷
挽巷 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:31

    This would be a greedy approach:

    1. Calculate a "score" matrix of order n X m, where score[i][j] is the total deduction of points in the matrix if position (i,j) is bombed. (Max score of a point is 9 and min score is 0)

    2. Moving row wise, find and pick the first position with highest score (say (i,j)).

    3. Bomb (i,j). Increase bomb count.

    4. If all elements of the original matrix are not zero, then goto 1.

    I have my doubts that this is the optimal solution though.

    Edit:

    The Greedy approach I posted above, while it works, most probably doesn't give us the optimal solution. So I figured should add some elements of DP to it.

    I think we can agree that at any point of time, one of the positions with the highest "score" (score[i][j] = total deduction of points if (i,j) is bombed) must be targeted. Starting with this assumption, here's the new approach:

    NumOfBombs(M): (returns the minimum number of bombings required)

    1. Given a Matrix M of order n X m. If all elements of M are zero, then return 0.

    2. Calculate the "score" matrix M.

      Let the k distinct positions P1,P2,...Pk (1 <= k <= n*m), be the positions in M with the highest scores.

    3. return (1 + min( NumOfBombs(M1), NumOfBombs(M2), ..., NumOfBombs(Mk) ) )

      where M1,M2,...,Mk are the resulting matrices if we bomb positions P1, P2, ..., Pk respectively.

    Also, if we want the order of positions to nuke in addition to this, we would have to keep track of the results of "min".

提交回复
热议问题