Python数据结构——图形结构
- 图:一种多对多的非线形数据结构;
- 图的应用:网络规划,地图规划;
- 图的遍历:广度优先 (BFS) 、深度优先 (DFS);
- 图的类别:无向图 (GRAPH) 、有向图 (DIGRAPH);
- 有向图:有向完全图,边长 n*(n-1) 个边;
强连通分支:最大的相互连通分支;
包含初度和入度;
<1,2> - 无向图:无向图,边长 n*(n-1)/2 个边;
连通分支:最大的相互连通分支;
(1,2) - 图的存储方式:是一个对称矩阵,保存下三角或上三角矩阵即可;
领结矩阵法:行看出度,列看入度;
领结矩阵法
- 图保存到矩阵中
def graph_transform_array(graph, array):
for i in range(len(graph)):
for j in range(len(array)):
tmp_i = graph[i][0]
tmp_j = graph[i][1]
array[tmp_i][tmp_j] = 1
return array
- 矩阵数据转为图
def array_transform_graph(array):
new_data = []
for i in range(len(array)):
for j in range(len(array[i])):
tmp_i = i
tmp_j = j
if array[tmp_i][tmp_j] == 1:
new_data.append([tmp_i, tmp_j])
return new_data
- 主函数
def graph_transform_array(graph, array):
for i in range(len(graph)):
for j in range(len(array)):
tmp_i = graph[i][0]
tmp_j = graph[i][1]
array[tmp_i][tmp_j] = 1
return array
def array_transform_graph(array):
new_data = []
for i in range(len(array)):
for j in range(len(array[i])):
tmp_i = i
tmp_j = j
if array[tmp_i][tmp_j] == 1:
new_data.append([tmp_i, tmp_j])
return new_data
if __name__ == '__main__':
new_array = [[0] * 6 for i in range(6)]
graph_array = [[1, 2], [2, 1], [1, 5], [5, 1], [2, 3], [3, 2], [2, 4], [4, 2], [3, 4], [4, 3]]
graph_array_one = []
new_array = graph_transform_array(graph_array, new_array)
print("图形结构保存到数组: ")
for i in range(len(new_array)):
print("\t", new_array[i])
graph_array_one = array_transform_graph(new_array)
print("数组转为图形结构: ", graph_array_one)
总结
- 领结矩阵法保存的数据需要提前开辟较大内存,也导致内存浪费;