Graphs
In computer science, a graph is a non-linear data structure consisting of a collection of vertices (or nodes) and edges. Each edge connects a pair of vertices and represents a relationship between them.
Graphs are widely used in various domains, including computer networking, social networks, and transportation systems. They provide a powerful way to model real-world relationships and solve complex problems.
To represent a graph in computer memory, there are several approaches, such as adjacency matrix and adjacency list. One common way is to use an adjacency list
, which is a collection of linked lists or arrays that store the neighbors of each vertex.
Here's an example of creating and printing a graph using Python:
1if __name__ == '__main__':
2 class Graph:
3 def __init__(self):
4 self.graph = {}
5
6 def add_vertex(self, vertex):
7 if vertex not in self.graph:
8 self.graph[vertex] = []
9
10 def add_edge(self, vertex1, vertex2):
11 if vertex1 in self.graph and vertex2 in self.graph:
12 self.graph[vertex1].append(vertex2)
13 self.graph[vertex2].append(vertex1)
14
15 def print_graph(self):
16 for vertex in self.graph:
17 print(vertex, '->', self.graph[vertex])
18
19 # Creating a graph
20 g = Graph()
21
22 # Adding vertices
23 g.add_vertex('A')
24 g.add_vertex('B')
25 g.add_vertex('C')
26 g.add_vertex('D')
27
28 # Adding edges
29 g.add_edge('A', 'B')
30 g.add_edge('B', 'C')
31 g.add_edge('C', 'D')
32
33 # Print the graph
34 g.print_graph()
In this example, we create a graph with four vertices and three edges. We then print the graph, which displays the relationships between the vertices.
The output of the code will be:
1A -> ['B']
2B -> ['A', 'C']
3C -> ['B', 'D']
4D -> ['C']
xxxxxxxxxx
g.print_graph()
if __name__ == "__main__":
class Graph:
def __init__(self):
self.graph = {}
def add_vertex(self, vertex):
if vertex not in self.graph:
self.graph[vertex] = []
def add_edge(self, vertex1, vertex2):
if vertex1 in self.graph and vertex2 in self.graph:
self.graph[vertex1].append(vertex2)
self.graph[vertex2].append(vertex1)
def print_graph(self):
for vertex in self.graph:
print(vertex, "->", self.graph[vertex])
# Creating a graph
g = Graph()
# Adding vertices
g.add_vertex('A')
g.add_vertex('B')
g.add_vertex('C')
g.add_vertex('D')
# Adding edges