The key insight into solving this problem is that the answer can be computed easily using just the locations of the three objects in the scene.

To simplify things, imagine there is no rock. In this case, the answer is just the difference in $x$ coordinate between the barn and lake, plus the difference in $y$ coordinate (minus one, since the endpoints don't count). This is sometimes known as "Manhattan" distance, since in downtown Manhattan the streets form a grid and you can only get from one location to another by moving along the $x$ or $y$ directions following the grid, not diagonally.

If we add the rock back to the picture, this actually rarely affects the answer, since we can always route around the rock unless the rock is in the same vertical or horizontal line as the barn and lake and lies between the two, in which case our path takes two additional steps to route around the rock.

My C++ code for solving the problem is below. It should be straightforward to translate to other languages.

#include <iostream> #include <fstream> #include <cmath> using namespace std; int barn_i, barn_j, rock_i, rock_j, lake_i, lake_j; int main(void) { ifstream fin ("buckets.in"); for (int i=0; i<10; i++) { string s; fin >> s; for (int j=0; j<10; j++) { if (s[j] == 'B') { barn_i = i; barn_j = j; } if (s[j] == 'R') { rock_i = i; rock_j = j; } if (s[j] == 'L') { lake_i = i; lake_j = j; } } } ofstream fout ("buckets.out"); int dist_br = abs(barn_i - rock_i) + abs(barn_j - rock_j); int dist_bl = abs(barn_i - lake_i) + abs(barn_j - lake_j); int dist_rl = abs(rock_i - lake_i) + abs(rock_j - lake_j); // Check for special case where rock is between barn and lake if ((barn_i==lake_i || barn_j==lake_j) && dist_bl == dist_br + dist_rl) fout << dist_bl + 1 << "\n"; else fout << dist_bl - 1 << "\n"; return 0; }