Skip to content

Commit

Permalink
Fix weakly_connected_components() performance on graph view (networkx…
Browse files Browse the repository at this point in the history
…#7586)

* Fix weakly_connected_components() performance

* Applied the same fix for connected.py
  • Loading branch information
gregory-shklover committed Aug 6, 2024
1 parent 89718e0 commit 2516c15
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
13 changes: 7 additions & 6 deletions networkx/algorithms/components/connected.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,10 @@ def connected_components(G):
"""
seen = set()
n = len(G)
for v in G:
if v not in seen:
c = _plain_bfs(G, v)
c = _plain_bfs(G, n, v)
seen.update(c)
yield c

Expand Down Expand Up @@ -148,11 +149,12 @@ def is_connected(G):
For undirected graphs only.
"""
if len(G) == 0:
n = len(G)
if n == 0:
raise nx.NetworkXPointlessConcept(
"Connectivity is undefined for the null graph."
)
return sum(1 for node in _plain_bfs(G, arbitrary_element(G))) == len(G)
return sum(1 for node in _plain_bfs(G, n, arbitrary_element(G))) == len(G)


@not_implemented_for("directed")
Expand Down Expand Up @@ -193,13 +195,12 @@ def node_connected_component(G, n):
For undirected graphs only.
"""
return _plain_bfs(G, n)
return _plain_bfs(G, len(G), n)


def _plain_bfs(G, source):
def _plain_bfs(G, n, source):
"""A fast BFS node generator"""
adj = G._adj
n = len(adj)
seen = {source}
nextlevel = [source]
while nextlevel:
Expand Down
6 changes: 3 additions & 3 deletions networkx/algorithms/components/weakly_connected.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,10 @@ def weakly_connected_components(G):
"""
seen = set()
n = len(G) # must be outside the loop to avoid performance hit with graph views
for v in G:
if v not in seen:
c = set(_plain_bfs(G, v))
c = set(_plain_bfs(G, n, v))
seen.update(c)
yield c

Expand Down Expand Up @@ -164,15 +165,14 @@ def is_weakly_connected(G):
return len(next(weakly_connected_components(G))) == len(G)


def _plain_bfs(G, source):
def _plain_bfs(G, n, source):
"""A fast BFS node generator
The direction of the edge between nodes is ignored.
For directed graphs only.
"""
n = len(G)
Gsucc = G._succ
Gpred = G._pred
seen = {source}
Expand Down

0 comments on commit 2516c15

Please sign in to comment.