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))


posted @ 2016-07-10 23:17  Salaku  阅读(1799)  评论(0编辑  收藏  举报