Problem description:
Hammy the hamster found a building with seeds. Help him collect them all.
The building is arranged in a matrix of rooms, with seeds in some rooms. Once in the building, Hammy will only run in a straight line, all the way through the building and collects all the seeds on that line. The building has many entrances and Hammy can enter at any row or column as he wishes.
He wants to collect all the seeds in the building with as few runs as possible.
Here is a sample layout of the building:
+---+---+---+---+---+
| * | | * | | |
+---+---+---+---+---+
| * | * | | | |
+---+---+---+---+---+
| * | | | | * |
+---+---+---+---+---+
| | | | * | |
+---+---+---+---+---+
| | | | * | |
+---+---+---+---+---+
This building has 25
rooms (5X5
) but only 8 rooms
have seeds (rooms containing '*
').
We need to find the minimum runs to collect all the seeds.
My approach:
I tried to solve it with some Greedy Approach
, here it is:
1) Start with row/column that contains maximum rooms of seeds (For example: column 1 for here).
2) Updating rows/columns (no of rooms that contain seeds).
3) Repeating steps 1 & 2 until all the seeds are collected.
So, for this example when I apply my approach,
It starts with Column 1
(it contains 3 rooms),
after updating, next will be Column 4
,
Here is the building situation right now,
+--+---+---+--+---+
| | | * | | |
+--+---+---+--+---+
| | * | | | |
+--+---+---+--+---+
| | | | | * |
+--+---+---+--+---+
| | | | | |
+--+---+---+--+---+
| | | | | |
+--+---+---+--+---+
Now three rooms contain seeds and all on different rows
or columns
, I needs to take all of them, as a result I finished with 5 runs
, which is the maximum
(taking all rows or all columns is always an answer withing thinking about the seeds at all). Without any calculation anyone can reach here. Runs containing all rows or columns.
But this problem can be solved in 4 runs.
I'm looking for an approach/algorithm to find the minimum runs (which rows and/or columns I need to run).