Skip to content

Commit cb603fa

Browse files
committed
Allow users to convert the graph to adjacency matrix.
1 parent fffe5f0 commit cb603fa

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

cyaron/graph.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,24 @@ def __init__(self, point_count, directed=False):
4040
self.directed = directed
4141
self.edges = [[] for i in range(point_count + 1)]
4242

43+
def to_matrix(self, **kwargs):
44+
"""to_matrix(self, **kwargs) -> list[list[Any]]
45+
Convert the graph to adjacency matrix.
46+
**kwargs(Keyword args):
47+
int default = -1 -> the default value when the edge does not exist.
48+
Any output(Edge)
49+
= lambda edge: edge.weight
50+
-> the mapping from edges to values in matrix.
51+
Note that the index start from 0 and the values in the Column 0 or the Row 0 are always the default.
52+
"""
53+
default = kwargs.get("default", -1)
54+
output = kwargs.get("output", lambda edge: edge.weight)
55+
n = len(self.edges)
56+
matrix = [[default for _ in range(n)] for _ in range(n)]
57+
for edge in self.iterate_edges():
58+
matrix[edge.start][edge.end] = output(edge)
59+
return matrix
60+
4361
def to_str(self, **kwargs):
4462
"""to_str(self, **kwargs) -> str
4563
Convert the graph to string with format. Splits with "\n"

0 commit comments

Comments
 (0)