Breadth/Depth First search algorithm-Python implementation

Source: Internet
Author: User

1. Figure

definition : A graph (graph) consists of a set of edges between a vertex with a poor non-empty set and a vertex, usually expressed as: g (v,e), where G represents a graph, V is a set of vertices in Figure g, and E is a collection of edges in Figure G.


The simple point is that the graph consists of nodes and edges. A node can be directly connected to many nodes, which are called neighbors.

For example, a binary tree is a simple diagram:

More detailed information can be found in: https://www.cnblogs.com/polly333/p/4760275.html

2. Algorithm 1). Breadth-First search:

Breadth-First search algorithm (breadth-SEARCH,BSF), the idea is:

  • 1. Starting at a vertex V, first access point V
  • 2. Access to V in turn after access to each of the unknown adjacency points;
  • 3. The neighboring points are then accessed from these adjacency points, respectively, and the adjacent points of the first visited vertices are accessed before the neighboring points of the vertices to be accessed;
  • 4. Until the adjacency point of all the visited vertices in the graph is accessed;
  • 5. If there are still vertices in the graph that are not accessed, you will need to select another vertex that has not been visited as the new starting point, repeating the process until all the vertices in the diagram have been accessed.

In other words, the breadth-first search traversal graph is based on V, from near to far, and then to V with a path and a path length of ... the vertex.


For example, the BFS access order is:

A->b->c->d->e->f

2). Depth-First search:

The depth-first search for graphs (Depth first search, DFS), and the tree's pre-order traversal are very similar.

It's thought:

  • 1. Starting at vertex V, first access the vertex;
  • 2. The depth-first search traversal graph is then taken from each of its inaccessible adjacency points in turn;
  • 3. Until all the vertices in the diagram that are connected to V are accessed.
  • 4. If there are other vertices that are not accessed at this point, select an unreachable vertex as the starting point, repeating the process until all vertices in the graph are accessed

For example, the BFS access order is:

A->b->d->e->c->f

3. Code
#-*-Coding:utf-8-*-#/usr/bin/pythonfrom Collections Import Dequeimport Sysclass Graph (object): Def __init__ (Self, *        args, **kwargs): Self.order = [] #visited order Self.neighbor = {} def add_node (Self, node): Key,val = node if not isinstance (Val, list): Print (' node value should is a list ') #sy S.exit (' failed for wrong input ') Self.neighbor[key] = Val def broadth_first (self, root): if root            ! = None:search_queue = Deque () search_queue.append (root) visited = [] Else:            Print (' root is None ') return-1 while Search_queue:person = Search_queue.popleft ()                Self.order.append (person) if (not visited) and (person in Self.neighbor.keys ()): Search_queue + = Self.neighbor[person] Visited.append (person) def depth_first (self, root): if R            Oot! = None:Search_queue = Deque () search_queue.append (root) visited = [] Else:print (' Root is ' None ') return-1 while Search_queue:person = Search_queue.popleft () self.order.a Ppend (person) if (not visited) and (person in Self.neighbor.keys ()): TMP = SELF.NEIGHB                 Or[person] Tmp.reverse () for index in Tmp:search_queue.appendleft (index) Visited.append (person) #self. Order.append (person) def clear (self): Self.order = [    ] def node_print (self): for index in Self.order:print (index, end= ") if __name__ = = ' __main__ ': g = Graph () g.add_node (' 1 ', [' One ', ' one ', ' one ', ' ' three ') ') G.add_node ((' One ', [' first ', ' second ', ' third ')]) G.add_node (( ' Both ', [' 1 ', ' 2 ', ' 3 '])) G.broadth_first (' 1 ') print (' Broadth search first: ') print (", end=") g.node_print () G.clear () pRint (' \n\ndepth Search first: ') print (', end= ') g.depth_first (' 1 ') G.node_print () print ()  

PS: The above code needs to run with python3.x, python2.x does not support print keyword parameters

PS2: The above code is somewhat imperfect, if you have the method of improvement, please leave a message, thank you very much!

Breadth/Depth First search algorithm-Python implementation

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.