Skip to content

Commit 2419c1f

Browse files
committed
图论基础类的实现和深度优先搜索的实现
0 parents  commit 2419c1f

File tree

8 files changed

+252
-0
lines changed

8 files changed

+252
-0
lines changed

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
.idea
2+
composer.lock
3+
*.log
4+
.ipynb_checkpoints

Graph/AdjacencyList.py

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
"""
2+
@author: Alex
3+
4+
@file: AdjacencyList.py
5+
@time: 2019/10/20 19:12
6+
"""
7+
class AdjList:
8+
9+
def __init__(self, filename):
10+
self.V = 0 # 顶点数
11+
self.E = 0 # 边数
12+
self.adj = None
13+
with open(filename) as f:
14+
line_num = 0 # 第一行是顶点数和边数
15+
for line in f:
16+
if line_num == 0:
17+
v, e = line.strip().split()
18+
self.V = int(v)
19+
self.E = int(e)
20+
self.adj = [[] for i in range(self.V)] # 创建二维数组即邻接表
21+
else:
22+
# 读取边 写入邻接表
23+
v1, v2 = line.strip().split()
24+
# 转化为整数
25+
v1 = int(v1)
26+
v2 = int(v2)
27+
self.adj[v1].append(v2)
28+
self.adj[v2].append(v1)
29+
line_num += 1
30+
31+
def get_graph_information(self):
32+
"""
33+
打印图的邻接表
34+
:return:
35+
"""
36+
print("V={}, E={}".format(self.V, self.E))
37+
for i, v in enumerate(self.adj):
38+
print("{} : {}".format(i, v))
39+
40+
def validateVertex(self, v):
41+
"""
42+
验证顶点取值
43+
:param v:
44+
:return:
45+
"""
46+
if v<0 or v>=self.V:
47+
raise ValueError("v值超出范围")
48+
49+
def hasEdge(self, v, w):
50+
"""
51+
判断两个顶点是否存在
52+
:param v: 第一个顶点
53+
:param w: 第二个顶点
54+
:return: true or false
55+
"""
56+
self.validateVertex(v)
57+
self.validateVertex(w)
58+
return w in self.adj[v]
59+
60+
def degree(self, v):
61+
"""
62+
求某个顶点的度
63+
:param v:
64+
:return:
65+
"""
66+
self.validateVertex(v)
67+
return len(self.adj[v])
68+
69+
70+
def graphDFS(self):
71+
visited = [False for i in range(self.V)]
72+
pre_order = [] # 前序遍历结果
73+
post_order = [] # 后序遍历结果
74+
75+
def dfs(v):
76+
# 标记v顶点已经遍历过了
77+
visited[v] = True
78+
# 添加
79+
pre_order.append(v)
80+
for w in self.adj[v]:
81+
if visited[w] == False:
82+
dfs(w)
83+
post_order.append(v)
84+
dfs(0)
85+
return pre_order,post_order
86+
87+
if __name__ == '__main__':
88+
adjm = AdjList("../g.txt")
89+
adjm.get_graph_information()
90+
print(adjm.hasEdge(0,4))
91+
print(adjm.degree(1))
92+
print(adjm.graphDFS())

Graph/AdjacencyMatrix.py

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
"""
2+
@author: Alex
3+
4+
@file: AdjacencyMatrix.py
5+
@time: 2019/10/20 18:31
6+
"""
7+
# 邻接矩阵
8+
class AdjMatrix:
9+
10+
def __init__(self, filename):
11+
self.V = 0 # 顶点数
12+
self.E = 0 # 边数
13+
self.adj = None
14+
with open(filename) as f:
15+
line_num = 0 # 第一行是顶点数和边数
16+
for line in f:
17+
if line_num == 0:
18+
v, e = line.strip().split()
19+
self.V = int(v)
20+
self.E = int(e)
21+
# self.adj = [[0] * self.V] * self.V # 该创建方式不正确 修改任何一个元素都会改变整个列表
22+
self.adj = [([0] * self.V) for i in range(self.V)] # 创建二维数组即邻接矩阵
23+
else:
24+
# 读取边 写入邻接矩阵
25+
v1, v2 = line.strip().split()
26+
# 转化为整数
27+
v1 = int(v1)
28+
v2 = int(v2)
29+
self.adj[v1][v2] = 1
30+
self.adj[v2][v1] = 1
31+
line_num += 1
32+
33+
def get_graph_information(self):
34+
"""
35+
打印图的邻接矩阵
36+
:return:
37+
"""
38+
print("V={}, E={}".format(self.V, self.E))
39+
print(adjm.adj)
40+
41+
def validateVertex(self, v):
42+
"""
43+
验证顶点取值
44+
:param v:
45+
:return:
46+
"""
47+
if v<0 or v>=self.V:
48+
raise ValueError("v值超出范围")
49+
50+
def hasEdge(self, v, w):
51+
"""
52+
判断两个顶点是否存在
53+
:param v: 第一个顶点
54+
:param w: 第二个顶点
55+
:return: true or false
56+
"""
57+
self.validateVertex(v)
58+
self.validateVertex(w)
59+
return self.adj[v][w]==1
60+
61+
def degree(self, v):
62+
"""
63+
求某个顶点的度
64+
:param v:
65+
:return:
66+
"""
67+
self.validateVertex(v)
68+
return sum(self.adj[v])
69+
70+
def AdjMatrixDFS(self):
71+
visited = [False for i in range(self.V)]
72+
pre_order = [] # 前序遍历结果
73+
post_order = [] # 后序遍历结果
74+
75+
def dfs(v):
76+
# 标记v顶点已经遍历过了
77+
visited[v] = True
78+
# 添加
79+
pre_order.append(v)
80+
for w in self.adj[v]:
81+
if visited[w] == False:
82+
dfs(w)
83+
post_order.append(v)
84+
for i in range(self.V):
85+
if visited[i] == False:
86+
dfs(i)
87+
return pre_order,post_order
88+
89+
if __name__ == '__main__':
90+
adjm = AdjMatrix("../g.txt")
91+
adjm.get_graph_information()
92+
print(adjm.hasEdge(6, 6))
93+
print(adjm.degree(1))
94+
print(adjm.AdjMatrixDFS())

Graph/__init__.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
"""
2+
@author: Alex
3+
4+
@file: __init__.py.py
5+
@time: 2019/10/20 18:30
6+
"""
7+

Graph/test.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
"""
2+
@author: Alex
3+
4+
@file: test.py
5+
@time: 2019/10/20 19:03
6+
"""
7+
8+
adj = [[0, 1, 0, 1, 0, 0, 0], [1, 0, 1, 0, 0, 0, 1], [0, 1, 0, 1, 0, 1, 0], [1, 0, 1, 0, 1, 0, 0], [0, 0, 0, 1, 0, 1, 0], [0, 0, 1, 0, 1, 0, 1], [0, 1, 0, 0, 0, 1, 0]]
9+
10+
print(sum(adj[0]))

g.txt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
7 9
2+
0 1
3+
0 3
4+
1 2
5+
1 6
6+
2 3
7+
2 5
8+
3 4
9+
4 5
10+
5 6

graph_basic.ipynb

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "code",
5+
"execution_count": null,
6+
"metadata": {},
7+
"outputs": [],
8+
"source": []
9+
}
10+
],
11+
"metadata": {
12+
"kernelspec": {
13+
"display_name": "Python 3",
14+
"language": "python",
15+
"name": "python3"
16+
},
17+
"language_info": {
18+
"codemirror_mode": {
19+
"name": "ipython",
20+
"version": 3
21+
},
22+
"file_extension": ".py",
23+
"mimetype": "text/x-python",
24+
"name": "python",
25+
"nbconvert_exporter": "python",
26+
"pygments_lexer": "ipython3",
27+
"version": "3.7.3"
28+
}
29+
},
30+
"nbformat": 4,
31+
"nbformat_minor": 2
32+
}

readme.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
## 1.介绍
2+
3+
图论算法python实现,封装图的邻接矩阵和邻接表的基础类,实现深度优先搜索(前序和后序)和广度优先搜索,图的各种应用方面的实现,哈密顿图,有向图算法,最短路径算法,欧拉回路和欧拉路径,网络流,匹配问题等等

0 commit comments

Comments
 (0)