0

Recently I took a test in the theory of algorithms. I had a normal best first search algorithm (code below).

from queue import PriorityQueue

# Filling adjacency matrix with empty arrays
vertices = 14
graph = [[] for i in range(vertices)]


# Function for adding edges to graph
def add_edge(x, y, cost):
    graph[x].append((y, cost))
    graph[y].append((x, cost))


# Function For Implementing Best First Search
# Gives output path having the lowest cost
def best_first_search(source, target, vertices):
    visited = [0] * vertices
    pq = PriorityQueue()
    pq.put((0, source))
    print("Path: ")
    while not pq.empty():
        u = pq.get()[1]
        # Displaying the path having the lowest cost
        print(u, end=" ")
        if u == target:
            break

        for v, c in graph[u]:
            if not visited[v]:
                visited[v] = True
                pq.put((c, v))
    print()


if __name__ == '__main__':
    # The nodes shown in above example(by alphabets) are
    # implemented using integers add_edge(x,y,cost);
    add_edge(0, 1, 1)
    add_edge(0, 2, 8)
    add_edge(1, 2, 12)
    add_edge(1, 4, 13)
    add_edge(2, 3, 6)
    add_edge(4, 3, 3)

    source = 0
    target = 2
    best_first_search(source, target, vertices)

He brings out Path: 0 1 0 2 (path sum — 8), it's correct.

My teacher suggested that I remake the code so that it looks for the local minimum path, i.e. Path: 0 1 2 (path sum — 13).

I need greedily take the shortest edge from the current node to an unvisited node and I don't really understand how to do it right.

  • [Best first search algorithm](https://i.imgur.com/IF4OTs5.png) – Joachim Gotzz Jan 13 '22 at 10:02
  • [Algorithm proposed by the teacher](https://imgur.com/a/PLL1QSe) – Joachim Gotzz Jan 13 '22 at 10:03
  • Do you want the shortest path, i.e. Dijkstra's algorithm? Or do you want to greedily take the shortest edge from the current node to an unvisited node? Right now your code is somewhere in between, and the question and examples don't make clear what you want either. – Thomas Jan 13 '22 at 10:06
  • @Thomas, greedily take the shortest edge from the current node to an unvisited node. – Joachim Gotzz Jan 13 '22 at 10:09

1 Answers1

0

Since this is homework, I won't spell out the entire code for you.

For best-first search, you don't need a priority queue. You just need to track which nodes you have visited, and which node you are currently at. While your current node is not the target node, find the shortest edge that leads to an unvisited node, and set your current node to the node at the other end of that edge.

Thomas
  • 174,939
  • 50
  • 355
  • 478