make the full circular path, shortest path exercise?

后端 未结 8 1513
耶瑟儿~
耶瑟儿~ 2021-02-04 22:27

I got this question in an interview and I was not able to solve it.

You have a circular road, with N number of gas stations. You know the ammount of gas

8条回答
  •  悲&欢浪女
    2021-02-04 23:08

    This is optimized case of @George Duckett's answer.

    • Choose and remember your start station.
    • Loop(1) through stations clockwise.
      • Get a fuel.
      • If you have enough fuel, go to next station, decrease remaining fuel amount, continue loop(1)

    If you reached your start station - problem solved.

    If on some station you do not have enough fuel to reach next one

    • Remember your end station.
    • Distance_to_start = 0, fuel_to_start = 0
    • Loop(2) from your start station counterclockwise.
      • Add available fuel and distance to next station to your counters
      • If fuel_to_start > distance_to_start, you have some excess fuel. Mark this station as your new start and go to loop(1) again - may be you can go ahead now.
      • Otherwise, continue loop(2)

    If you had gone counterclockwise to already visited station - bad luck, there is not enough fuel on stations to go full circle.

提交回复
热议问题