Skip to content

fix(graph): distinguish self-loops from other incident edges - #2240

Open
Shubham-Padkonde wants to merge 1 commit into
trekhleb:masterfrom
Shubham-Padkonde:fix/graph-self-loop-lookup
Open

Shubham-Padkonde wants to merge 1 commit into
trekhleb:masterfrom
Shubham-Padkonde:fix/graph-self-loop-lookup

Conversation

@Shubham-Padkonde

Copy link
Copy Markdown

Looking up an edge from a vertex to itself currently returns its first incident edge, even if that edge leads to another vertex. Match both endpoints, and share that lookup with hasNeighbor.

For directed edges A→B (-3) and A→A (9), Bellman-Ford previously reported distance -3 to A even though there is no negative cycle. It now reports 0. An undirected adjacency matrix also now uses the actual self-loop's weight.

Addresses the self-loop lookup part of #2230. The separate parallel-edge policy question in that issue is unchanged. This fix is independent of #2187's negative-cycle detection proposal.

Validation: three new regressions fail before the fix. All 178 suites / 590 tests pass with coverage, including 100% coverage of GraphVertex.js. npm run lint passes.

AI-assisted contribution.

moshejs added a commit to moshejs/javascript-algorithms that referenced this pull request Oct 25, 2026
The same fix and equivalent regression tests are proposed in trekhleb#2240.
Leave it there to avoid duplicate review and merge conflicts. The
Rabin-Karp rolling hash change from the previous commit stays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant