Python Data Structure-Details of graph depth-first and breadth-first instances, python Data Structure

Source: Internet
Author: User

Python Data Structure-Details of graph depth-first and breadth-first instances, python Data Structure

This document describes how to prioritize the depth and breadth of a python data structure. Share it with you for your reference. The details are as follows:

First, there is a concept: backtracking

The Backtracking Method (exploration and backtracking) is an optimization search method that searches forward based on the optimization conditions to achieve the goal. However, when you find that the previous selection is not optimal or fails to reach the target, you can return to the previous step and re-select the target. This technology will return to the backtracing method if you fail to get the target, vertices that meet backtracing conditions are called backtracing points ".

Deep Priority Algorithm:

(1) access the initial vertex v and mark that the vertex v has been accessed.
(2) Find the first adjacent vertex w of vertex v.
(3) If vertex v's adjacent vertex w exists, continue to execute; otherwise, go back to v and find another unaccessed adjacent vertex of v.
(4) If vertex w has not been accessed, access vertex w and Mark vertex w as accessed.
(5) continue to find the wi of the next adjacent vertex of vertex w. If the value of v is wi, go to step (3 ). Until all vertices in the connected graph have been accessed.

Breadth-first algorithm:

(1) vertex v enters the queue.
(2) When the queue is not empty, the execution continues; otherwise, the algorithm ends.
(3) the output queue obtains the vertex v of the queue header, accesses vertex v, and marks that vertex v has been accessed.
(4) Search for the first adjacent vertex col of vertex v.
(5) If the col of the adjacent vertex of v is not accessed, col is entered into the queue.
(6) continue to find another adjacent vertex col of vertex v and go to step (5 ). Until all unaccessed adjacent contacts of vertex v are processed. Go to step (2 ).

Code:

#!/usr/bin/python# -*- coding: utf-8 -*-class Graph(object):  def __init__(self,*args,**kwargs):    self.node_neighbors = {}    self.visited = {}  def add_nodes(self,nodelist):    for node in nodelist:      self.add_node(node)  def add_node(self,node):    if not node in self.nodes():      self.node_neighbors[node] = []  def add_edge(self,edge):    u,v = edge    if(v not in self.node_neighbors[u]) and ( u not in self.node_neighbors[v]):      self.node_neighbors[u].append(v)      if(u!=v):        self.node_neighbors[v].append(u)  def nodes(self):    return self.node_neighbors.keys()  def depth_first_search(self,root=None):    order = []    def dfs(node):      self.visited[node] = True      order.append(node)      for n in self.node_neighbors[node]:        if not n in self.visited:          dfs(n)    if root:      dfs(root)    for node in self.nodes():      if not node in self.visited:        dfs(node)    print order    return order  def breadth_first_search(self,root=None):    queue = []    order = []    def bfs():      while len(queue)> 0:        node = queue.pop(0)        self.visited[node] = True        for n in self.node_neighbors[node]:          if (not n in self.visited) and (not n in queue):            queue.append(n)            order.append(n)    if root:      queue.append(root)      order.append(root)      bfs()    for node in self.nodes():      if not node in self.visited:        queue.append(node)        order.append(node)        bfs()    print order    return orderif __name__ == '__main__':  g = Graph()g.add_nodes([i+1 for i in range(8)])g.add_edge((1, 2))g.add_edge((1, 3))g.add_edge((2, 4))g.add_edge((2, 5))g.add_edge((4, 8))g.add_edge((5, 8))g.add_edge((3, 6))g.add_edge((3, 7))g.add_edge((6, 7))print "nodes:", g.nodes()order = g.breadth_first_search(1)order = g.depth_first_search(1)

Result:

Nodes: [1, 2, 3, 4, 5, 6, 7, 8]

Breadth First:
[1, 2, 3, 4, 5, 6, 7, 8]

Depth first:

[1, 2, 4, 8, 5, 3, 6, 7]

I hope this article will help you with Python programming.

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.