make the full circular path, shortest path exercise?

后端 未结 8 1515
耶瑟儿~
耶瑟儿~ 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:12

    One easy way of solving this is using a brute force method. i.e. try every posibility and throw out ones that don't work.

    i.e. Start at each gas station in turn (repeat below for each starting station).

    • Have a varible that defines current gas level.
    • Loop through each gas station, in a clockwise order.
      1. Fill up your gas (increment gas by gas station amount).
      2. Check you can move to the next station (gas >= gasToMoveToNextStationNeeded)
        • If not, this isn't a solution, so move to the next starting location.
        • If so, subtract that amount of gas used, then keep going until you reach the start again.
      3. If you get back to the starting gas station you have an answer.

    Edit As per @Vash's answer, As an improvement when deciding where to start, discount stations that don't have enough gas themselves to get to the next station and working through starting stations in order of amount of gas (descending).


    Note, this assumes we visit all gas stations. Will need refinement for skipping gas stations if you need an optimal solution (question doesn't specify this).

提交回复
热议问题