Counting the Number of Visible Pairs of Mountains

Viewed 84

I am trying to determine the number of mountains that are mutually visible. The heights of the mountains are in a doubly-circular linked list such as {1,2,3,4,5}.

Visibility depends on:

  1. Adjacent Mountains are visible.
  2. The 2 Visible Mountains A & B must not be the same mountain.
  3. If A & B are not adjacent, the lower height of the 2 is Hmin. If all the mountains between A & B are less than or equal to Hmin, A & B are still visible.

Currently, my thought process is to have a marker pointer say pointing at 1, and a target pointer pointing at 3. Thus, the minimum height between the 2 pointers is 1, which is the lower of the 2 mountains.

Then, I'll create a cursor pointer to check if the heights of the mountains in between are less than or equal to the minimum height. If true, it means that we can see the other mountain if we choose to stand at either mountain 1 or 3.

Thus, I created a nested loop, where the outer loop is having the marker pointer to iterate over all the mountains. While the inner loop is having the target pointer iterate over all the mountains, except the ones that are adjacent to the marker.

My issue is that with mountains {5, 2, 2, 4, 3}, if my target = 4 & marker = 5, I'll record the result. But I am double counting when my marker = 5, and target = 4. Is there any way I can rectify this? Thank you.

0 Answers
Related