Graphs
A graph is a data structure that consists of a set of nodes (also known as vertices) and a set of edges that connect pairs of nodes. Graphs are used to represent networks of connections or relationships between objects, making them incredibly useful in various applications, from social network analyses to route optimization and beyond.
Graphs can be directed or undirected. In a directed graph, edges have a direction, indicating a one-way relationship, while in an undirected graph, the edges do not have a direction, signifying a bi-directional relationship. Additionally, graphs can be weighted or unweighted, where a weight represents the cost, distance, or any measurable attribute associated with traversing from one node to another.
Example in Python
In Python, graphs can be represented using dictionaries, where keys represent nodes, and values represent lists of adjacent nodes. Here's a simple example of an undirected graph:
This snippet defines a graph and prints it, showcasing the connections between nodes.
Example in C#
In C#, one way to represent a graph is by using a class to define a node and a list to track its edges or adjacent nodes. Here is a simple implementation:
This code demonstrates creating a simple graph with three nodes and connecting them together. Through these examples, you can appreciate the versatility and power of graphs in solving complex programming challenges.
Last updated
Was this helpful?