You are on page 1of 2

from 

queue import PriorityQueue
v = 14
graph = [[] for i in range(v)]
def gbfs(source, target, node):
  visited = [False] * node
  pq = PriorityQueue()
  pq.put((0, source))
  visited[source] = True
  while pq.empty() == False:
    u = pq.get()[1]
    print(u, end=" ")
    if u == target:
      break
    for v, c in graph[u]:
      if visited[v] == False:
        visited[v] = True
        pq.put((c, v))
def addedge(x, y, cost):
  graph[x].append((y, cost))
  graph[y].append((x, cost))
addedge(1,2, 22)
addedge(1, 3, 9)
addedge(2,3, 10)
addedge(2,4, 2)
addedge(3,4, 4)

source = 1
target = 4
print("Greedy BFS: ")
gbfs(source, target, v)

visited = set()
def dfs(visited, graph, node):
  if node not in visited:
    print(node, end=" ")
    visited.add(node)
    for child in graph[node]:
      dfs(visited, graph, child)
dfs(visited, graph, 'aqsa')
g = nx.Graph(graph)
nx.draw_networkx(g)
plt.figure(figsize=[7,7])
plt.show()
pos = nx.spring_layout(g)
print(pos)

You might also like