Mark As Completed Discussion

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:

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:

SNIPPET
1A -> ['B']
2B -> ['A', 'C']
3C -> ['B', 'D']
4D -> ['C']
PYTHON
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment