Graphs are a popular data structure used in computer science and mathematics for representing a collection of objects (vertices) and their connections (edges). A weighted graph is a type of graph where each edge has a weight or a value assigned to it. In this article, we will explore the concept of weighted graph data structure , their applications, and implementation using Python programming language.

Introduction to Weighted Graphs

In a weighted graph, each edge is assigned a numerical value or weight that represents some cost or distance associated with that edge. For example, in a map, the distance between two cities can be represented by the weight assigned to the edge connecting those cities.

Weighted graphs are used in a variety of applications, including:

Types of Weighted Graphs

There are two main types of weighted graphs:

  1. Directed weighted graph: In this type of graph, each edge has a direction and a weight associated with it. This means that the edge represents a one-way connection between two vertices, and the weight represents the cost of traversing that edge in that direction.
  2. Undirected weighted graph: In this type of graph, each edge has a weight associated with it, but there is no direction. This means that the edge represents a connection between two vertices that can be traversed in both directions, and the weight represents the cost of traversing that edge in either direction.

Implementing Weighted Graphs in Python

In Python, we can implement a weighted graph using a dictionary and a list. The dictionary is used to store the vertices of the graph and their adjacent vertices, while the list is used to store the edges and their weights.

Let’s see an example of implementing a directed weighted graph in Python:

class WeightedGraph:
    def __init__(self):
        self.vertices = {}

    def add_vertex(self, vertex):
        self.vertices[vertex] = []

    def add_edge(self, start_vertex, end_vertex, weight):
        self.vertices[start_vertex].append((end_vertex, weight))

In this implementation, the WeightedGraph class has two methods: add_vertex and add_edge. The add_vertex method adds a new vertex to the graph, while the add_edge method adds a new edge with a weight between two vertices.

To create a new weighted graph, we can do the following:

g = WeightedGraph()
g.add_vertex('A')
g.add_vertex('B')
g.add_vertex('C')
g.add_edge('A', 'B', 2)
g.add_edge('B', 'C', 3)
g.add_edge('A', 'C', 1)

This creates a directed weighted graph with three vertices (‘A’, ‘B’, and ‘C’) and three edges with weights (2, 3, and 1) connecting them.

Dijkstra’s Algorithm for Shortest Path

One of the most common algorithms used with weighted graphs is Dijkstra’s algorithm for finding the shortest path between two vertices. This algorithm works by starting at the source vertex and iteratively exploring the neighboring vertices to find the shortest path to each one.

Let’s see an example of implementing Dijkstra’s algorithm in Python:

import heapq

def dijkstra(graph, start_vertex):
    distances = {vertex: float('inf') for vertex in graph.vertices}
    distances[start_vertex] = 0
    pq = [(0, start_vertex)]

    while len(pq) > 0:
        current_distance, current_vertex

(current_vertex) = heapq.heappop(pq)

    if current_distance > distances[current_vertex]:
        continue

    for neighbor, weight in graph.vertices[current_vertex]:
        distance = current_distance + weight

        if distance < distances[neighbor]:
            distances[neighbor] = distance
            heapq.heappush(pq, (distance, neighbor))

return distances

Conclusion

In summary, a weighted graph is a type of graph where each edge has a weight or value assigned to it. Weighted graphs are used in a variety of applications, including network routing algorithms, shortest path algorithms, traffic flow analysis, scheduling and resource allocation, and game AI and pathfinding. In Python, we can implement a weighted graph using a dictionary and a list, and we can use Dijkstra’s algorithm to find the shortest path between two vertices.

FAQs

  1. What is the difference between a weighted graph and an unweighted graph?
  1. What is Dijkstra’s algorithm used for?
  1. What is the time complexity of Dijkstra’s algorithm?
  1. Can a weighted graph be cyclic?
  1. What are some real-world examples of weighted graphs?

Leave a Reply

Your email address will not be published. Required fields are marked *