Worldscope

Konigsberg Bridge Problem in Graph Theory

Palavras-chave:

Publicado em: 29/08/2025

The Königsberg Bridge Problem and Euler's Solution

The Königsberg bridge problem, a historical puzzle originating in the city of Königsberg (now Kaliningrad, Russia), asks whether it is possible to traverse all seven bridges of the city exactly once. This seemingly simple question led to the foundation of graph theory. This article will delve into the problem, Euler's elegant solution, and a practical implementation using code.

Fundamental Concepts / Prerequisites

Before diving into the solution, understanding a few fundamental concepts from graph theory is essential:

  • Graph: A graph consists of vertices (nodes) connected by edges.
  • Vertex (Node): Represents an entity or location in the graph.
  • Edge: A connection between two vertices. In this case, each bridge is represented by an edge connecting two landmasses (vertices).
  • Degree of a Vertex: The number of edges connected to a vertex.
  • Eulerian Path: A path in a graph that visits every edge exactly once.
  • Eulerian Circuit (or Cycle): An Eulerian path that starts and ends at the same vertex.

Implementation in Python

Here's a Python implementation to determine if an Eulerian path (or cycle) exists in a graph represented as an adjacency list.


def is_eulerian(graph):
    """
    Checks if a given graph has an Eulerian path or cycle.

    Args:
        graph: A dictionary representing the graph's adjacency list.  Keys are vertices,
               and values are lists of their neighbors.

    Returns:
        -1: If the graph is not connected.
        0: If the graph has an Eulerian cycle.
        1: If the graph has an Eulerian path (but not a cycle).
        2: If the graph has no Eulerian path or cycle.
    """

    # Check if the graph is connected using Depth First Search (DFS)
    def dfs(graph, start_node, visited):
        visited[start_node] = True
        for neighbor in graph[start_node]:
            if not visited[neighbor]:
                dfs(graph, neighbor, visited)

    vertices = list(graph.keys())
    if not vertices:
        return 2 # Empty graph is considered to have no Eulerian path

    # Find the first vertex with edges to use as starting point for DFS
    start_node = vertices[0]
    for v in vertices:
        if graph[v]:
            start_node = v
            break

    visited = {v: False for v in vertices}
    dfs(graph, start_node, visited)

    # Check if all vertices with edges are visited, if not, then graph is not connected
    for v in vertices:
        if graph[v] and not visited[v]:
            return -1  # Not connected


    # Check for odd degree vertices
    odd_degree_count = 0
    for vertex in graph:
        if len(graph[vertex]) % 2 != 0:
            odd_degree_count += 1

    if odd_degree_count > 2:
        return 2  # No Eulerian path or cycle
    elif odd_degree_count == 2:
        return 1  # Eulerian path
    else:
        return 0  # Eulerian cycle



# Example usage:  Königsberg bridge problem
konigsberg_graph = {
    'A': ['B', 'C'],
    'B': ['A', 'C', 'D'],
    'C': ['A', 'B', 'D'],
    'D': ['B', 'C']
}

result = is_eulerian(konigsberg_graph)

if result == -1:
  print("Graph is not connected.")
elif result == 0:
  print("Graph has an Eulerian cycle.")
elif result == 1:
  print("Graph has an Eulerian path (but not a cycle).")
else:
  print("Graph has no Eulerian path or cycle.")

Code Explanation

The Python code implements Euler's theorem to determine the existence of an Eulerian path or cycle:

`is_eulerian(graph)` function:

  • Takes an adjacency list representation of a graph as input. The graph is a dictionary where keys are vertices and values are lists of their adjacent vertices.
  • First check if the graph is connected using Depth First Search (DFS) algorithm
  • `dfs(graph, start_node, visited)`: Performs DFS traversal of the graph, marking visited nodes.
  • Counts the number of vertices with an odd degree. Euler's theorem states:
  • If the graph is not connected, return -1
  • If there are more than two vertices with odd degree, no Eulerian path or cycle exists (returns 2).
  • If there are exactly two vertices with odd degree, an Eulerian path exists (returns 1).
  • If all vertices have even degree, an Eulerian cycle exists (returns 0).

The example uses the Königsberg graph. Since all four landmasses (A, B, C, D) have an odd degree (3), the `is_eulerian` function correctly identifies that there's no Eulerian path.

Complexity Analysis

The time and space complexity of the solution is as follows:

  • Time Complexity: The `is_eulerian` function has a time complexity of O(V + E) where V is the number of vertices and E is the number of edges, dominated by the Depth-First Search (DFS) algorithm.
  • Space Complexity: The space complexity is O(V) due to the `visited` set used in the DFS traversal and the recursive call stack during the DFS.

Alternative Approaches

Another way to determine the existence of an Eulerian path is using Hierholzer's Algorithm to actually construct such a path (if it exists). While Hierholzer's Algorithm constructs the path, which can be valuable in some applications, it has a higher constant factor in its complexity because it needs to traverse the graph multiple times. The approach presented focuses solely on determining existence which is often sufficient for problems similar to Königsberg.

Conclusion

The Königsberg bridge problem elegantly illustrates the power of graph theory. Euler's solution demonstrated that the existence of an Eulerian path or cycle depends on the degree of the vertices. The Python code provides a practical way to determine the existence of such a path, providing insights into graph connectivity and degree distribution.