Python data structure graph depth first and breadth first examples

@This article comes from the public number: csdn2299, like to pay attention to the public number programmer academy
This article describes the depth-first and breadth-first usage of the graph of the Python data structure. Share with you for your reference. details as follows:

First there is a concept: backtracking

The backtracking method (exploration and backtracking method) is an optimal search method, which searches forward according to the optimal conditions to achieve the goal. However, when exploring a certain step, it is found that the original choice is not good or does not reach the goal, and then one step is returned to re-select. This technique of returning and going back is a retrospective method, and a certain point of the state that meets the retrospective condition This is called the "backtrack point".

Depth-first algorithm:

(1) Visit the initial vertex v and mark the vertex v has been visited.
(2) Find the first adjacent vertex w of vertex v.
(3) If the adjoining vertex w of vertex v exists, continue execution; otherwise, go back to v and find another unvisited adjoining point of v.
(4) If vertex w has not been visited yet, visit vertex w and mark vertex w as visited.
(5) Continue to find the next adjacent vertex wi of vertex w. If v takes the value of wi, go to step (3). Until all vertices in the connected graph have been visited.

Breadth first algorithm:

(1) Vertex v enters the queue.
(2) When the queue is not empty, continue to execute, otherwise the algorithm ends.
(3) Get out of the queue to get the head vertex v; visit the vertex v and mark the vertex v has been visited.
(4) Find the first adjacent vertex col of vertex v.
(5) If the adjacent vertex col of v has not been visited, col is enqueued.
(6) Continue to find another new adjacent vertex col of vertex v, go to step (5). Until all the neighboring points of vertex v that have not been visited 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 order
if __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]
Thank you very much for reading
. I chose self-study python when I was in college. After working, I found that I owe a bad foundation to the computer. I do n’t have an education. This is
impossible. , Can only make up for it the day after tomorrow, so he opened his own road of counterattack outside of coding, constantly learning the core knowledge of python, in-depth study of computer basics, and sorted it out. Beyond coding, keep growing!
In fact, there are not only technology here, but also things beyond those technologies. For example, how to be an exquisite programmer, rather than "cock silk", the programmer itself is a noble existence, isn't it? [Click to join] Want to be yourself, want to be a noble person, come on!

34 original articles published · Liked12 · Visitors 20,000+

Guess you like

Origin blog.csdn.net/chengxun03/article/details/105476955