We present an optimal and efficient algorithm for finding a shortest path in an elastic optical network. The algorithm is an adaptation of the Dijkstra shortest path algorithm, where we take into account the spectrum continuity and contiguity constraints, and a limit on the path length. The adaptation redefines the node label in the Dijkstra algorithm, allows for revisiting nodes even at a higher cost for different slices, avoids loops, and prunes worse labels. The algorithm is generic and agnostic of a specific spectrum allocation policy, as it finds the largest set of available slices from which slices can be allocated in any way. We describe and motivate the algorithm design, and point to our freely-available implementation using the Boost Graph Library. We carried out 8100 simulation runs for large, random and realistic networks, and found that the probability of establishing a connection using the proposed algorithm can be even twice as large as the probability of establishing a connection using the edge-disjoint shortest paths, and the Yen K shortest paths.