Python Dijkstra算法


( VISIT_WHITE, VISIT_GRAY, VISIT_BLACK ) = ( 0, 1, 2 )
NO_ROAD = 1 << 31 


class CityNode:
    
    def __init__( self ):
        
        self.m_iDist = 1 << 31
        self.m_iParent = 0
        self.m_visit = VISIT_WHITE



def init( graph ):
    
    graph[0][1] = 15; graph[0][3] = 2; graph[0][4] = 12
    graph[1][2] = 6; graph[2][6] = 9; graph[3][2] = 8;
    graph[3][5] = 4; graph[4][6] = 3; graph[5][6] = 10
    graph[5][4] = 5; graph[6][1] = 4



def dijkstra( graph, start_pos ):
    
    city_num = len( graph )
    INF      = 1 << 31
    city_arr = [ CityNode() for index in range( city_num ) ]
    count = 0
    city_arr[start_pos].m_iDist = 0
    
    while count < city_num:
        
        temp_min = INF
        next_pos = -1
        
        for index in range( city_num ):
            if temp_min > city_arr[index].m_iDist \
               and city_arr[index].m_visit != VISIT_BLACK:
                
                temp_min = city_arr[index].m_iDist
                next_pos = index
                
        city_arr[next_pos].m_visit = VISIT_BLACK
        
        for index in range( city_num ):
            if graph[next_pos][index] != NO_ROAD \
               and city_arr[index].m_visit != VISIT_BLACK \
               and city_arr[index].m_iDist > city_arr[next_pos].m_iDist + graph[next_pos][index]:
                
                city_arr[index].m_iDist = city_arr[next_pos].m_iDist + graph[next_pos][index]
                city_arr[index].m_visit = VISIT_GRAY
                
        count += 1
        
    for index in range( city_num ):
        print index, city_arr[index].m_iDist



if __name__ == '__main__':
    num = 7
    graph = [ [ NO_ROAD for col_index in range( num ) ]for raw_index in range( num ) ]
    
    init( graph )
    
    dijkstra( graph, 0 )


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值