Back to community
Preview — replies are illustrative, not live

How do you approach a graph problem when you're stuck?

Asked 2h agoViewed 1,204 times

Every time I see a graph problem in a contest or interview, I can identify that it's a graph problem, but I freeze the moment my first BFS attempt doesn't immediately work.

Does anyone have a mental checklist they run through? Something like: is it weighted, is it directed, do I need shortest path or just reachability, should I think in terms of states instead of nodes?

Would love to hear how more experienced people break the problem down before writing any code.

algorithmsgraphsbfs-dfs
SK

Sophea K.

Algorithms mentor

3 Answers

Accepted answer

My checklist: 1) draw the graph on paper first, 2) ask if it's weighted, 3) ask if you need shortest path, all paths, or just connectivity, 4) only then pick BFS/DFS/Dijkstra. Writing code before answering those three questions is what usually causes the freeze.

RS

Ratanak S.

Community moderator · answered 1h ago

Adding to this — a lot of "graph" problems are secretly state-space search. If the nodes aren't obvious, ask what a "state" is in the problem (position + keys collected, position + time, etc).

VM

Vichet M.

ML practitioner · answered 45m ago

This thread should be pinned forever, genuinely bookmarking it.

LC

Lina C.

Security enthusiast · answered 20m ago

Posting answers is launching soon. In the meantime, browse courses or challenges.