python如何表示图_python表示无向图

g_text = """

{

0:[6,2,1,5],

1:[0],

2:[0],

3:[5,4],

4:[5,6,3],

5:[3,4,0],

6:[0,4],

7:[8],

9:[11,10,12],

10:[9],

11:[9,12],

12:[9,11],

}

"""

## 深度优先

def dfs(g,n):

visited =set()

where_from = dict()

def __dfs(n):

visited.add(n)

for x in g.get(n,[]):

if x not in visited:

where_from[x]=n

__dfs(x)

__dfs(n)

return where_from

## 广度优先

def bfs(g,n):

visited = set()

where_from = dict()

queue = []

queue.append(n)

while queue:

head = queue.pop(0)

visited.add(head)

for x in g.get(head,[]):

if x not in visited:

where_from[x] = head

queue.append(x)

return where_from

## 获得路径

def get_path(where_from,_from,to):

try:

path = []

x = to

while x != _from:

path.insert(0,x)

x = where_from[x]

path.insert(0,x)

return path

except:

return []

## 连通部分计数

def connected_component(g):

visited = set()

cc = dict()

where_from = dict()

count = 0

def __dfs(n):

visited.add(n)

cc[n] = count

for x in g.get(n,[]):

if x not in visited:

where_from[x] = n

__dfs(x)

for x in g:

if x not in visited:

count += 1

__dfs(x)

return cc

## 判断环路

def has_cycle(g):

cycle = []

visited = set()

where_from = dict()

def dfs(u,v):

visited.add(u)

for x in g.get(u,[]):

if x not in visited:

where_from[x]=u

dfs(x,u)

elif x!=v :

path = get_path(where_from,x,u)

if path:

cycle.append(path+[x])

for x in g:

if x not in visited:

dfs(x,x)

return cycle

## 两色

def two_color(g):

color = dict()

visited = set()

two_color_able =True

def dfs(n):

visited.add(n)

for x in g.get(n,[]):

if x not in visited:

color[x] = not color[n]

dfs(x)

elif color[x] == color[n]:

two_color_able = False

for x in g:

if x not in visited:

color[x] = True

dfs(x)

return two_color_able,color

if __name__ == "__main__":

g = eval(g_text)

print(two_color(g))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值