There is a graph G with no permissions. Use a vertex s as the input parameter to find the shortest path from S to other vertices. In this way, you only need to calculate the number of edges contained in the path.
For example, a word ladder problem converts only one letter at a time to find the shortest path from fool to sage.
A word can be converted into a graph:
First, find the vertex with a distance of 1 from fool:
Then we can find the vertex 2 away from fool:
Finally, search for all vertices:
The method for searching a graph is called the breadth-first search: the vertices closest to the start point are first searched, and the farthest vertices are finally searched.
Def unweighted (G, V): queue = [] path_length = {} path_length [v] = 0 queue. append (v) while queue: V = queue. pop (0) for I in v. getneighbors (): If I not in path_length: path_length [I] = path_length [v] + 1 queue. append (I) Return path_length