Python non-recursive traverse graph

Source: Internet
Author: User

classQueue:def __init__(self,max_size): Self.max_size=Int (max_size) Self.queue= []    defput (self,data):ifSelf.max_size >0:ifself.full ():RaiseValueError ('Queue is full!')            Else: Self._put (data)defGet (self):ifSelf._queue_size () >0:result=self._get () Empty_flag=FalseElse: Result=None Empty_flag=TruereturnresultdefEmpty (self):ifSelf._queue_size () = =0:returnTrueElse:            returnFalsedefFull (self):ifSelf._queue_size () = =self.max_size:returnTrueElse:            returnFalsedef_put (self,data): self.queue.append (data)def_get (self): result=Self.queue[0] Self.queue.pop (0)returnresultdef_queue_size (self):returnLen (self.queue)defTravel_dbfs (Self,first_node):#depth traversal of graphsStack_lsit =[] Visited=[] Stack_lsit.append (First_node) visited.append (First_node) whileLen (stack_lsit) >0:x= Stack_lsit[-1]         forWinchx.neighbor_list:if  notWinchvisited:Print(W.data) visited.append (w) stack_lsit.append (w ) Break        ifSTACK_LSIT[-1] = =X:stack_lsit.pop ()defTravel_bfs (Self,first_node):#breadth traversal of graphsQueue = Queue (100000) visited=[] Queue.put (First_node) visited.append (First_node) while  notqueue.empty (): v=queue.get () I= 1Try: w=V.neighbor_list[i]exceptindexerror:w=None whileW:if  notWinchvisited:Print(W.name) visited.append (w) queue.put (w) I= I+1Try: w=V.neighbor_list[i]exceptindexerror:w=NoneclassGraphnode:def __init__(self,data): Self.neighbor_list=[] Self.data= Data


Depth-first traversal and breadth-first traversal
Depth-First traversal

1. Recursive definition of depth-first traversal


Suppose that the initial state of a given figure g is that all vertices have never been visited. If you select a vertex in G as the initial starting point (source point), then the depth-first traversal can be defined as follows: first access to the starting point V, and mark it as visited, and then start from V to search for the V of each adjacency point W. If W has not been accessed, the depth-first traversal is continued with W as the new starting point, until all vertices (also known as vertices reachable from the source point) in the graph that have a path to the source point v have been accessed. If you still have an unreachable vertex in the diagram, select another vertex that has not yet been accessed to repeat the process as the new source point until all the vertices in the diagram have been accessed.

The depth-first traversal of a graph is similar to a tree's pre-sequence traversal. The search method used is characterized by searching the depth direction as much as possible first. This search method is called depth-first search (Depth-first searches). Accordingly, traversing a graph with this method is naturally referred to as the depth-first traversal of graphs.

2. Basic realization Idea:

(1) Access vertex v;

(2) A vertex w is selected from the inaccessible adjacency point of V, and the depth-first traversal is carried out from W;

(3) Repeat the above two steps until all the vertices in the diagram that are connected to the V are accessed.

3. Pseudo-code

Recursive implementation

(1) Access vertex v;visited[v]=1;//algorithm before execution visited[n]=0

(2) The first adjacency point of a w= vertex v;

(3) while (W exists)

if (w not accessed)

The algorithm is executed recursively from vertex W.
W= the next adjacency point of Vertex v;

Non-recursive implementation

(1) Stack s initialization; visited[n]=0;

(2) Access vertex v;visited[v]=1; vertex v into the stack s

(3) while (stack s not empty)

x= stack s top element (not out of stack);

If (exists and finds the adjacency point of an inaccessible x W)

Access to W;visited[w]=1;

W into the stack;

Else

x out stack;

Breadth-First traversal

1. Breadth-First traversal definition

The breadth-first traversal algorithm of graphs is a hierarchical search process, and the tree's sequence traversal algorithm is similar, it also needs a queue to maintain the traversed vertex order, in order to access the vertices of the adjacent vertices in the sequence of the team.


2. Basic Realization Ideas

(1) Vertex v into the queue.

(2) Execution continues when the queue is non-empty, otherwise the algorithm ends.

(3) Out of the queue to get the team overhead point v; Access Vertex v and Mark Vertex v has been accessed.

(4) Find the first adjacency vertex of Vertex v Col.

(5) If the adjacent vertex of V Col is not visited, Col is queued.

(6) Continue to find another new adjacency vertex of Vertex v Col, go to step (5).

Until all the unreachable adjacency points of Vertex v have been processed. Go to step (2).

The breadth-first traversal graph is based on the Vertex v as the starting point, from near to far, in order to access and V has a path and the path length of 1, 2, ... The vertex. In order for the adjacency point of the first access vertex to be accessed before the adjacency point of the accessed vertex, set the vertex that the queue stores access to.

3. Pseudo-code

(1) Initialize queue q;visited[n]=0;

(2) Access vertex v;visited[v]=1; vertex v into queue q;

(3) while (queue Q is not empty)

v= Queue Q of the enemy elements out of the team;

w= the first adjacency point of Vertex v;

while (W exists)

If W is not accessible, the vertex w is accessed;

Visited[w]=1;

Vertex w into the queue q;

W= the next adjacency point of Vertex v.

Python non-recursive traverse graph

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.