A graph G = (V, E) is composed of vertex set V and edge set E. Each edge is a vertex pair (v, w), where v, w, and V. If the vertex is ordered, the graph is a directed graph.
A path in the figure is a vertex sequence w1, w2, w3,..., wk, making (wi, wi + 1) ε E, 1 <= I <= k. The path length is the number of edges in the path.
If a path exists from each vertex to other vertex in an undirected graph, the path is connected. Directed Graphs of this nature are strongly connected. Remove the direction from the arc of the directed graph.
If the graph is connected, the directed graph is weakly connected.
Simple two-dimensional array representation of an image
Represent with an adjacent matrix. For each edge (u, v), set A [u] [v] = 1, otherwise it is 0. if the edge has a permission, set the array element to the permission. The required space is bytes (V2 ).
If the graph is dense (with many edges), the adjacent matrix is an appropriate representation. If it is sparse, the better solution is to use the adjacent table.
Graph joining table Representation
For each vertex, use a table to store all adjacent vertices. At this time, the space requirement is O (E + V ).
class Vertex(object): def __init__(self,key): self.id=key self.adj={} def addNeighbor(self,nbr,weight=0): self.adj[nbr]=weight def getNeighbors(self): return self.adj.keys() def getId(self): return self.id def getWeight(self,key): return self.adj[key]class Graph(object): def __init__(self): self.vertexlist={} self.size=0 def addVertex(self,key): vertex=Vertex(key) self.vertexlist[key]=vertex self.size+=1 return vertex def getVertex(self,key): return self.vertexlist.get(key) def __contains__(self,key): if key in self.vertexlist: return True else: return False def addEdge(self,f,t,weight=0): if f not in self.vertexlist: self.addVertex(f) if t not in self.vertexlist: self.addVertex(t) self.vertexlist[f].addNeighbor(self.vertexlist[t],weight) def getVertices(self): return self.vertexlist.keys() def __iter__(self): return iter(self.vertexlist.values())