create a program that says the minimum amount of contacts

Given a graph describing the relationships of the social network, create a program that tells the minimum amount of contacts to reach John.

Input:

The first line of the input indicates how many are the n vertices of the graph (2 ≤ n ≤ 100). The next n lines each represent the information of a vertex in the format: id,A,v1,v2,⋯,vA, where id is an integer identifying the vertex, A is the number of edges connected to this vertex, and each vi ≠ id is an integer identifying a vertex adjacent to id. The last line has two ids, separated by space, that represent you and John, respectively.

Exit:

Present the minimum amount of contacts needed to reach John, if possible, the message “Forevis alonis…” otherwise.

Observation:
Each network user is represented by a unique id. In the first example, John is already one of your contacts. In the second case, you have to go through users 2 and 3 to reach the idol. In the latter case, it is not possible to contact you…

create a program that says the minimum amount of contacts

My code for this problem so far has been this as I haven’t been able to solve the problem. Code:

graph = {}
for _ in range(int(input())):
  v, A, *neighbor = map(int,(input().split()))
  graph[v] = neighbor
I, John = map(int, input().split())

def shortest_way(origin, destination, path=[]):
  path.append(origin)
  if origin == destination:
    return path
  shorter = [] 
  for neighbors in graph[origin]:
    if neighbors not in path:
      outro_caminho = shortest_way(neighbors.destination.path[:])

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

One possible solution is to use one list as the current path and then once the destination is reached, to store save it in paths so that at the end you can compare all possible solutions and return the shortest one.

def shortest_way(origin, destination, path, paths):
  if origin == destination:
    path += [destination]
    paths.append(path)
    return paths
  for neighbor in graph[origin]:
    if neighbor not in path:
      shortest_way(neighbor, destination, path+[origin], paths)
  return paths

paths = shortest_way(I, John, [], [])
if not paths:
  print("Forevis alonis...")
print("shortest path =", min([len(i) for i in paths]))


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x