Textual Presentation of Graph Object
格式规定:
U:undirected 无向图
D:directed 有向图
W:weighted 有权重的
示例:(无向无权重图)
U 4
1 3
0 2
1 0
该图的邻接矩阵:
该图的邻接表:
输入样例:
graph_string = """\
U 17
1 2
1 15
1 6
12 13
2 15
13 4
4 5
"""
1.将上述字符串转换为邻接矩阵
from math import inf
def adjacent_matrix(graph_str):
lis = graph_str.split('\n')
lis.pop()
info = lis[0].split()#info[0]表示图的类型 info[1]表示点的个数
n = int(info[1])
ans = [[inf for i in range(n)] for j in range(n)]
if len(info) == 2: #无权重的图
if info[0] == 'D': #有向图
for i in range(1, len(lis)):
start, end = map(lambda x:int(x), lis[i].split())
ans[start][end] = 1
elif info[0] == 'U': #无向图
for i in range(1, len(lis)):
start, end = map(lambda x:int(x), lis[i].split())
ans[start][end] = 1
ans[end][start] = 1
elif len(info) == 3: #有权重的图
if info[0] == 'D': #有向图
for i in range(1, len(lis)):
start, end, weight = map(lambda x:int(x), lis[i].split())
ans[start][end] = weight
elif info[0] == 'U': #无向图
for i in range(1, len(lis)):
start, end, weight= map(lambda x:int(x), lis[i].split())
ans[start][end] = weight
ans[end][start] = weight
return ans
2. 将上述字符串转换为邻接表
def adjacency_list(graph_str):
lis = graph_str.split('\n')
lis.pop()
info = lis[0].split()
#info[0]表示图的类型 info[1]表示点的个数
ans = [[] for i in range(int(info[1]))]
if len(info) == 2: #无权重的图
if info[0] == 'D': #有向图
for i in range(1, len(lis)):
start, end = map(lambda x:int(x), lis[i].split())
tup = (end, None)
ans[start].append(tup)
elif info[0] == 'U': #无向图
for i in range(1, len(lis)):
start, end = map(lambda x:int(x), lis[i].split())
tup1 = (end, None)
tup2 = (start, None)
ans[start].append(tup1)
ans[end].append(tup2)
elif len(info) == 3: #有权重的图
if info[0] == 'D': #有向图
for i in range(1, len(lis)):
start, end, weight = map(lambda x:int(x), lis[i].split())
tup = (end, weight)
ans[start].append(tup)
elif info[0] == 'U': #无向图
for i in range(1, len(lis)):
start, end, weight= map(lambda x:int(x), lis[i].split())
tup1 = (end, weight)
tup2 = (start, weight)
ans[start].append(tup1)
ans[end].append(tup2)
return ans
3. 从邻接表转换为矩阵
def adjacent_list_to_matrix(adj_list):
n = len(adj_list)
ans = [[inf for i in range(n)] for j in range(n)]
for i, edges in enumerate(adj_list):
ans[i][i] = 0
for edge in edges:
end = edge[0]
weight = edge[1]
ans[i][end] = weight
return ans