DOJ logoDOJ
Problems
Recently added problemsSaved problems
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord-backed certification.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

Recognizing Convex Grid Graphs

Back to problem

Editorial

Let SSS be the set of given points. It is enough to verify all three conditions below.

  • For every fixed xxx-coordinate, the occurring yyy-coordinates are consecutive without gaps.
  • For every fixed yyy-coordinate, the occurring xxx-coordinates are consecutive without gaps.
  • The graph is connected.

First, these conditions are necessary. Consider two points (x,a)(x,a)(x,a) and (x,b)(x,b)(x,b) with the same xxx-coordinate. Their Manhattan distance is ∣a−b∣|a-b|∣a−b∣. 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 uuu and vvv. Assume that the path uses both rightward and leftward edges. Then it contains a subpath whose endpoints have the same xxx-coordinate and whose interior contains at least one horizontal edge. Since all points between the endpoints on that fixed xxx-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 xxx-coordinate changes in only one direction along a shortest path. By the same argument, the yy-coordinate also changes in only one direction. Hence the path length is exactly the Manhattan distance.

For the implementation, sort the point indices by (x,y)(x,y)(x,y). For every adjacent pair with the same xxx-coordinate, verify that their yyy-coordinates differ by exactly 111, and unite them in a DSU. Then sort by (y,x)(y,x)(y, 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 O(Nlog⁡N)O(N\log N)O(NlogN) because of the two sorts, and the memory complexity is O(N)O(N)O(N).

(x,y)(x,y)(x,y)
yyy
y
x
)
NO
YES