TC VegetableGarden

VegetableGarden

 * http://www.topcoder.com/stat?c=problem_statement&pm=7507&rd=10664

Summary
This problem seems to be pretty tricky (only 4 people got it right) but the solution is fairly short. It takes place on a rectangular grid. You have to walk around inspecting certain plots of land but not inspecting others.

From SRM 340, Division 1, Level 3 (1000 points).

Problem Statement
Your vegetable garden forms a rectangular grid of equal square plots. You've decided to inspect some of your plots. Starting at the top left corner, you will walk through the garden and return back to your starting point. All plots that lie inside the cycle of your path will be considered inspected. You are not allowed to walk inside the plots; you can only walk along their boundaries. Your path must not intersect itself. The boundaries are wide enough that you can walk along the same boundary multiple times without intersecting your own path.

You are given a String[] garden, where the j-th character of the i-th element represents the plot at row i, column j. The plots you would like to inspect are represented by uppercase 'I' characters. '.' characters represent plots you don't care about, and uppercase 'X' characters represent plots you must never inspect. Return a int[] where the i-th element is equal to the length of the shortest path that lets you inspect exactly i+1 plots marked with the letter 'I'. The number of elements in the return value must be equal to the number of 'I's in garden. Note that it is okay for '.' plots to be inspected, but 'X' plots must never be inspected.

Hints

 * The constraint "Your path must not intersect itself" can be ignored.
 * Given any square S, let R be any infinite ray leaving that square. Then after you return to the origin, S is inside your path if and only if your path intersects R an odd number of times.