A city is laid out as a grid with H rows and W columns. Each cell either holds one shop or is empty. Every shop sells a different item, and the price of an item is an integer from 1 to 9.
You start at cell (1,1) and walk to cell (H,W). From a cell you may move only to the cell on its right or the cell below it.
Every time you arrive at a cell, including the starting cell, you shop in this order.
- If the cell you arrived at holds a shop you have not bought from yet, you buy its item.
- Collect every cell that shares a side with the cell you arrived at and holds a shop you have not bought from yet. If there is at least one such cell, choose exactly one of them, skip it, and buy the item of every other collected cell. If there is no such cell, you buy nothing.
You buy from each shop at most once. In step 2 you choose the cell to skip freely each time. A shop you skipped is bought later anyway if you arrive next to it again.
Print the smallest amount of money you spend when the route and every skipped cell are chosen as well as possible.