This article mainly introduces the traversal function of Python based on the backtracking subset tree template, and analyzes the relevant operation techniques and precautions of Python using the backtracking subset tree template in the case of the graph traversal problem, and the friends can refer to the following
In this paper, we describe the traversal function of Python based on the backtracking subset tree template implementation diagram. Share to everyone for your reference, as follows:
Problem
A diagram:
A-and B
A-and C
B--C
B--D
B--E
C--A
C--D
D--C
E--F
F--C
F--D
A node E, which does not repeat through all the other nodes, goes back to the departure node E, which is called a path. Please find out all the possible paths.
Analysis
Visualize this diagram as follows:
This question relates to diagrams, which first consider the representation of the graph in that storage structure. Adjacency Matrix, adjacency table 、... are not very familiar.
Earlier in this article http://www.jb51.net/article/122927.htm has one of the most concise adjacency table representations.
The problem itself is then analyzed:
Obviously, the length of the solution of the problem is fixed, i.e. all path lengths are fixed: N (not returning to the departure node) or n+1 (back to the departure node)
Each node has its own adjacency node.
For a node, all its neighboring nodes can be regarded as the state space of this node. Traversing its state space, pruning, depth precedence recursively to the next node. Get!
At this point, it is obvious that the backtracking subset tree template is applied.
Code:
The traversal of the graph goes from one node to the start node without repeating all the other nodes. Find out all paths ' # with adjacency table graph n = 6 # node Number a,b,c,d,e,f = Range (n) # node Name graph = [ {b,c}, { c,d,e}, { a,d}, {c}, {f}, {c,d}]x = [0]* (n+1) # A solution (n+1 meta array, fixed length) x = [] # A set of solutions # Collision Detection def conflict (k): global n,graph,x # k node, whether previously Walk through if K < n and X[k] in X[:k]: return True # back to departure node if k = = N and x[k]! = x[0]: return True
return False # No conflict # graph Traversal def dfs (k): # Reached (solution x) k node global n,a,b,c,d,e,f,graph,x,x if k > N: # The length of the solution exceeds, has traveled n+ 1 nodes (k==n) print (x) #X if not back to the departure node . Append (x[:]) else: for node in graph[x[k-1]: # traversal node X[k] Adjacency node (all states of x[k] x[k] = node if not conflict (k): # Pruning dfs (k+1) # test x[0] = e # departure node DFS (1) # Start understanding the 2nd section in X Point
: