Have you heard the term "optimum", "optimisation"?
This is where it was inspired from. Why? Because the path a light travels ("optics"), is the "best" in a specific sense. This sense is described in Fermat's principle.
It states that a light ray will follow the path of least time (depending on the medium it is propagated).

The picture of the refraction of the pencil part inside the water cup, is exactly the result of this effect. Because light inside the water (which has a different refraction index than the air), makes the light take another path in order to minimise the time the path takes.
This is a basic principle of geometrical optics (meaning study of light as a geometrical ray and not as a wave as in electromagnetism or a particle as in quantum mechanics).
When Fermat's principle of geometrical optics is expressed in variational form, it arrives at your second formulation. When Fermat's principle is expressed as a stationary form it arrives at your first formulation. All these three formulations (i.e path of least time, stationary trajectory among neighbouring paths, least action), in this case express exactly the same thing thus are equivalent.