-1

There is a 2-d grid which contains chocolates in random cells.In one move ,i can take all the chocolates contained in one row or in one column.What will be the minimum number of moves required to take all the chocolates?

Example:cells containing chocolates are:

0 0
1 1
2 2

min. no of moves =3

0 0
1 0
0 1

min no of moves=2

I guess there is a greedy algo solution to this problem.But how to approach this problem?

nickie
  • 5,608
  • 2
  • 23
  • 37
RKTSP
  • 99
  • 1
  • 8
  • 1
    So what have you tried? How did it work? How did it *not* work? You might want to read [the Stack Overflow question checklist](http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist). – Some programmer dude Oct 08 '13 at 06:42
  • 2
    Answer to first example is two, just take the second row and then the third row. – john Oct 08 '13 at 06:42

2 Answers2

0

I think this is a variance of classic Set Cover problem which is proved to be NP-hard.

Therefore, a greedy algorithm could only get an approximation but not the optimal solution.

SaltyEgg
  • 1,498
  • 1
  • 15
  • 26
0

For this specific problem, it is not NP-hard. It can be solved in polynomial time. The solution is as below:

Transform the 2D grid to be a bipartite graph. The left side contains nodes represent row and the right side contains nodes represent column. For each cell containing chocolate, suppose it's coordinate is (x,y), add an edge linking row_x and column_y. After the bipartite graph is established, use Hungarian algorithm to get the maximum matching. Since in bipartite graph, the answer of maximum matching equals minimum vertex covering, the answer is exactly what you want.

The Hungarian algorithm is a O(V*E) algorithm. For more details, pls refer to Hungarian algorithm

For more information about bipartite graph, pls refer to Bipartite graph, you can find why maximum matching equals minimum vertex covering here.

PS: It's neither a greedy problem nor dynamic programming problem. It is a graph problem.

songlj
  • 927
  • 1
  • 6
  • 10