Graph Theory (iii) ------ breadth-first search and single-source no-Permission Shortest Path

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.