简体   繁体   中英

CodeFights: Dijkstra's Algorithm implementation

Considering this code fight problem:

Consider a big city located on n islands. There are bridges connecting the islands, but they all have only one-way traffic. To make matters worse, most of the bridges are closed at night, so there is at most one bridge with traffic going from any island A to any other island B.

There is a programmer who turns a penny by working nights as an Uber driver. One night his phone dies right after he picks up a rider going from island 0 to island (n - 1). He has the map of the city bridges in his laptop though (stored as a matrix of distances), so he decides to implement an algorithm that calculates the shortest path between those two islands and evaluate the cost based on the distance of the path. Assume that each mile of the trip is 1$.

I have decided to implement Dijkstra's algorithm to solve it:

def nightRoute(city):
    visited = [];
    visited.append(0);
    distance = [];
    for x in range(0, len(city)):
        distance.append(float("inf"));
    distance[0] = 0;

    while(len(visited) != len(city)):
        for i in visited:
            print visited;
            min = float("inf");
            minNode = -1;
            for j in range(0, len(city)):
                if ( j not in visited and city[i][j] != -1):
            if distance[j] > distance[i] + city[i][j]:
            distance[j] = distance[i] + city[i][j]
                    if distance[i] + city[i][j] <= min:
                        min = distance[i] + city[i][j];
                        minNode = j
            if(min != float("inf") and minNode != -1):
                visited.append(minNode);
    return distance[len(city)-1];

However when I run the code, it only passes 6/7 test cases (the last 3 test cases are hidden to me so i don't know what the inputs are).

Can anyone tell me what is wrong with my implementation of dijkstra's? Am i missing something in how dijkstras work?

You should find the visited node contains the minimum key (distance) in each iteration, instead of trying all visited nodes. Although the relaxation is still safe, you may put some of the nodes not having the optimal key to the visited set, hence compromises the result.

Furthermore, although I don't think this will change the result, it would be better to avoid comparing two float numbers using == or != .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM