Skip to content

Commit 95ca77d

Browse files
committed
Improve degree and nb_edges
1 parent 848a6f3 commit 95ca77d

1 file changed

Lines changed: 18 additions & 6 deletions

File tree

src/graph.jl

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -221,17 +221,27 @@ function neighbors(g::AdjacencyGraph{T,false}, v::Integer) where {T}
221221
return neighbors_v
222222
end
223223

224-
function degree(g::AdjacencyGraph, v::Integer)
225-
d = 0
226-
for u in neighbors(g, v)
227-
if u != v
228-
d += 1
224+
function degree(g::AdjacencyGraph{T,true}, v::Integer) where {T}
225+
S = pattern(g)
226+
rvS = rowvals(S)
227+
d = S.colptr[v+1] - S.colptr[v]
228+
for index in nzrange(S, v)
229+
row = rvS[index]
230+
if row >= v
231+
(row == v) && (d -= 1)
232+
break
229233
end
230234
end
231235
return d
232236
end
233237

234-
function nb_edges(g::AdjacencyGraph)
238+
function degree(g::AdjacencyGraph{T,false}, v::Integer) where {T}
239+
S = pattern(g)
240+
d = S.colptr[v+1] - S.colptr[v]
241+
return d
242+
end
243+
244+
function nb_edges(g::AdjacencyGraph{T,false}) where {T}
235245
ne = 0
236246
for v in vertices(g)
237247
for u in neighbors(g, v)
@@ -241,6 +251,8 @@ function nb_edges(g::AdjacencyGraph)
241251
return ne ÷ 2
242252
end
243253

254+
nb_edges(g::AdjacencyGraph{T,true}) where {T} = nnz(g.S) ÷ 2
255+
244256
maximum_degree(g::AdjacencyGraph) = maximum(Base.Fix1(degree, g), vertices(g))
245257
minimum_degree(g::AdjacencyGraph) = minimum(Base.Fix1(degree, g), vertices(g))
246258

0 commit comments

Comments
 (0)