This a question from a coding competition
The original question can be found here http://www.olympiad.org.za/olympiad/wp-content/uploads/2014/03/2013-PO-Question-Paper.pdf Question 5
SHORTEST PATH THROUGH THE HALL [by Alan Smithee of Hulsbos High]
The hall is packed wall to wall with rows of chairs, but in each row there are exactly two chairs missing. The chairs in each row have numbers from 1 to 100. Write a program that will calculate the length of the shortest path from the front to the back of the hall. Each chair is 1 unit wide and each row is 1 unit deep (from the front of a chair to the front of the chair behind it). It is not possible to move diagonally. You may start in front of any gap in the front row and end behind any gap in the last row. You always walk through the middle of a gap. Illustrated is the shortest path through a hall, with five rows of chairs. In the illustration the hall is only 10 chairs wide instead of 100. The first number in the input will contain the number n – the number of rows. The next n lines will have two numbers, separated by a space, indicating where the gaps are. Example Input: 5 3 6 2 8 4 5 7 8 3 10
I think I have an efficient algorithm that I think will work, but I'm not sure how to implement it into Java.
What I want to do is break up each choice into a search tree so for instance if the user input was:
number of rows: 3
Spaces : 4 7 2 9 8 11
Make 2 search trees:
4 7
2 9 2 9
8 11 8 11 8 11 8 11
And then find the path where the difference between each node is the smallest So in this case the shortest path would be in the second tree 7->9->8 with the total distance being 5 (||7-9|-8|) So my question is then
Is this acceptable algorithm given the problem
How would I implement either this algorithm or another in java
@JuanLopes Take for instance this example (0s represent a space).
Row6: 0 2 3 4 5 6 0 8 9
Row5: 0 2 3 4 5 6 0 8 9
Row4: 1 2 3 0 5 6 0 8 9
Row3: 1 2 3 0 5 6 0 8 9
Row2: 1 2 3 0 5 6 0 8 9
Row1: 1 2 3 0 5 6 0 8 9
What I understand from your algorithm is that it looks at each row individually. So through rows 1-4 the distance between each space to the next row is equal but when you get to row 5 if you went down the path where all the 4s were missing it would take you longer compared to going down the path with all the 7s missing, does your solution take that into account?