Let be the set of given points. It is enough to verify all three conditions below.
First, these conditions are necessary. Consider two points and with the same -coordinate. Their Manhattan distance is . A path of exactly this length cannot use a horizontal edge, so every intermediate lattice point must exist. The same argument applies to points with the same -coordinate. The graph must also be connected because every pair must have a finite graph distance.
Now suppose that all three conditions hold. Choose a shortest path between any two vertices and . Assume that the path uses both rightward and leftward edges. Then it contains a subpath whose endpoints have the same -coordinate and whose interior contains at least one horizontal edge. Since all points between the endpoints on that fixed -coordinate exist, the endpoints can be connected directly by a vertical path. This direct path is shorter than the chosen subpath, contradicting shortestness. Therefore the -coordinate changes in only one direction along a shortest path. By the same argument, the -coordinate also changes in only one direction. Hence the path length is exactly the Manhattan distance.
For the implementation, sort the point indices by . For every adjacent pair with the same -coordinate, verify that their -coordinates differ by exactly , and unite them in a DSU. Then sort by and perform the symmetric check. If any gap exists, the answer is . After both passes, the answer is exactly when all points belong to one DSU component.
The time complexity is because of the two sorts, and the memory complexity is .
NOYES