class list_node(object):
def __init__(self, val):
self.val = val
self.next = None
# 建立邻接表
def create_linjiebiao(data):
all_head = []
for i in range(1, 9):
all_head.append(list_node(i)) # 8个头
for i in data:
for j in all_head:
x = j
if i[0] == j.val:
newNode = list_node(i[1]) # 实例化节点
while x.next != None: # 插入新节点
x = x.next
x.next = newNode
return all_head
def show(all_head):
for i in all_head:
# 打印
while i != None:
print(i.val, end=' ')
i = i.next
print('')
'''
1=> 2 3
2=> 1 4 5
3=> 1 6 7
4=> 2 8
5=> 2 8
6=> 3 8
7=> 3 8
8=> 4 5 6 7
'''
def dfs(all_head, current, flag):
flag[current - 1] = 1 # 为1表示已经被遍历过
print('[%d]' % current, end=' ')
item = all_head[current - 1].next # item指向2节点
while item != None:
if flag[item.val - 1] == 0: # flag为0,表示没有访问过
dfs(all_head, item.val, flag)
item = item.next
if __name__ == '__main__':
data = [[1, 2], [2, 1], [1, 3], [3, 1],
[2, 4], [4, 2], [2, 5], [5, 2],
[3, 6], [6, 3], [3, 7], [7, 3],
[4, 8], [8, 4], [5, 8], [8, 5],
[6, 8], [8, 6], [8, 7], [7, 8], ]
flag = [0] * 8
all_head = create_linjiebiao(data)
show(all_head)
dfs(all_head, 1, flag)