Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Graph Theory Structures

Graph Theory Structures

In computer science, graphs are widely used to model social networks (users are nodes, friendships are edges), web links (pages are nodes, hyperlinks are edges), communication networks, and even path planning problems.

GraphIt is like a social network graph:

Imagine your city's transportation network: each location (such as home, school, mall) is aPoint, and the roads connecting these places arelines. A graph is the mathematical abstraction of such node-and-line relationships; it is a data structure used to representcomplex relationships between entities.

Real-life examples:

Scenario Other structures Graph structure
Social relationships Hard to express complex relationships Naturally expresses many-to-many relationships
Path planning Requires complex data structures Intuitively represents networks and paths
Dependency Relationship Hard to represent cyclic dependencies Easily handles complex dependencies
Network analysis Cannot express network topology Perfectly describes network structure

Basic Graph Terminology

Term define Life Analogy Representation
Vertex The basic unit in a graph A person in a social network V, u, v
Edge A line connecting two vertices A relationship between two people E, (u,v)
Degree The number of edges connected to a vertex The number of friends a person has deg(v)
Path A sequence of vertices A route from A to B v₁→v₂→…→vₙ
Cycle A path whose start and end are the same Leaving home and finally returning home v₁→v₂→…→v₁
Connected graph There is a path between any two nodes Everyone can reach each other
Weight A numeric attribute of an edge The distance between two cities w(u,v)

Classification of Graphs

Classification criterion Type Feature Application scenarios
Directionality Undirected graph Edges have no direction Friendships, road networks
Directed graph Edges have direction Following relationships, workflows
Weight Unweighted graph All edges have the same weight Social network relationships
Weighted graph Edges have different weights Map distances, network traffic
Connectivity Connected graph Any two nodes are reachable Transportation networks
Disconnected graph Isolated nodes exist Social groups
Cycles Acyclic graph No cycles Task dependencies, family trees
Cyclic graph Contains cycles Road networks

Graph Representation Methods

Adjacency Matrix

Feature Description Time Complexity Space complexity
Storage method 2D matrix
Check edge existence matrix[i][j] != 0 O(1)
Add an edge matrix[i][j] = weight O(1)
Delete an edge matrix[i][j] = 0 O(1)
Traverse adjacent vertices Scan a row/column O(V)
Space usage V×V matrix O(V²)

Adjacency list

Feature Description Time Complexity Space complexity
Storage method Array + linked list
Check edge existence Search in the linked list O(deg(v))
Add an edge Add to the linked list O(1)
Delete an edge Delete from the linked list O(deg(v))
Traverse adjacent vertices Traverse the linked list O(deg(v))
Space usage Vertex array + edge linked list O(V+E)

Basic concepts of graphs

A graph G consists of two sets:

Example

A simple graph example: representing social network friendships with a dictionary

Vertices: Alice, Bob, Charlie, Diana

Edges: representing the friendships between them

social_graph

=

{

   

'Alice'

:

[

'Bob'

,

'Charlie'

]

,

 

Alice is friends with Bob and Charlie

   

'Bob'

:

[

'Alice'

,

'Charlie'

,

'Diana'

]

,

   

'Charlie'

:

[

'Alice'

,

'Bob'

]

,

   

'Diana'

:

[

'Bob'

]

}

print

(

f

"Vertices (users): {list(social_graph.keys())}"

)

print

(

f

"Alice's friends (edges): {social_graph['Alice']}"

)

Output:

顶点(用户): ['Alice', 'Bob', 'Charlie', 'Diana']

Alice 的好友(边): ['Bob', 'Charlie']


Graph Classification and Important Concepts

Graphs can be classified into various types based on their edges; understanding these is fundamental to mastering graph theory.

Undirected vs Directed Graphs

Type Characteristics of an Edge Real-life analogy Example
Undirected graph An edge has no direction,(A, B) meaning A and B are connected to each other. Mutual friendship: if Alice is Bob's friend, then Bob must also be Alice's friend. Friendships in social networks, connections in circuits.
Directed graph An edge has direction,A -> B meaning a one-way connection from A to B. Weibo following: you can follow someone, but they may not follow you. Web hyperlinks, task dependencies, one-way streets.

Weighted graphs

In a weighted graph, each edge is assigned a numeric value (weight), which can represent distance, cost, time, or relationship strength.

Example

A weighted graph representing distances between cities (adjacency list form)

weighted_graph

=

{

   

'Beijing'

:

{

(

'Shanghai'

,

1200

)

,

(

'Tianjin'

,

100

)

}

,

 

The distance from Beijing to Shanghai is 1200, and to Tianjin is 100

   

'Shanghai'

:

{

(

'Beijing'

,

1200

)

,

(

'Hangzhou' (a Chinese city name)

,

200

)

}

,

   

'Tianjin'

:

{

(

'Beijing'

,

100

)

}

,

   

'Hangzhou' (a Chinese city name)

:

{

(

'Shanghai'

,

200

)

}

}

Key Terms


Graph storage methods

How to represent a graph in a computer? There are two main approaches.

Adjacency Matrix

Use a two-dimensional array (matrix)matrix to represent the graph.matrix[i][j] The value of i at vertex j represents the edge situation.

Example

Represent an undirected graph with an adjacency matrix

Vertices: 0-A, 1-B, 2-C

Edges: A-B, A-C

V

=

3

 

Number of vertices

adj_matrix

=

[

[

0

]

for

_

in

range

(

V

)

]

Add edge A-B (0-1)

adj_matrix

[

0

]

[

1

]

=

1

adj_matrix

[

1

]

[

0

]

=

1

 

An undirected graph needs the symmetric position set

Add edge A-C (0-2)

adj_matrix

[

0

]

[

2

]

=

1

adj_matrix

[

2

]

[

0

]

=

1

print

(

"Adjacency matrix:"

)

for

row

in

adj_matrix:

   

print

(

row

)

Output:

[0, 1, 1]

[1, 0, 0]

[1, 0, 0]

Adjacency list

Maintain a list (linked list, array, etc.) for each vertex, recording all vertices directly connected to it (and their weights).

Example

Represent the same undirected graph with an adjacency list (dictionary + list)

adj_list

=

{

   

'A'

:

[

'B'

,

'C'

]

,

 

A is connected to B and C

   

'B'

:

[

'A'

]

,

     

B is connected to A

   

'C'

:

[

'A'

]

       

C is connected to A

}

print

(

"Adjacency list:"

)

for

vertex

,

neighbors

in

adj_list.

items

(

)

:

   

print

(

f

"{vertex}: {neighbors}"

)


Graph Traversal Algorithms

Traversal is the foundation of graph algorithms, meaning systematically visiting every vertex in the graph.

There are two main strategies:

Breadth-first search

Breadth-First Search (BFS) is like a "water ripple spreading": starting from the initial node, it visits all direct neighbors first, then the neighbors' neighbors, and so on. It usesQueueto do so.

Algorithm steps:

  1. Put the starting vertex into a queue and mark it as visited.
  2. While the queue is not empty: a. Take out the front vertex v. b. Visit v all unvisited neighbors of it, put them into the queue and mark them as visited.
  3. Repeat step 2.

Example

from

collections

import

deque

def

bfs

(

graph

,

start

)

:

   

"""Traverse a graph with BFS, returning the visit order"""

    visited

=

set

(

[

start

]

)

 

Record visited vertices

    queue

=

deque

(

[

start

]

)

 

Initialize the queue

    result

=

[

]

           

Store the visit order

   

while

queue:

        vertex

=

queue.

popleft

(

)

        result.

append

(

vertex

)

       

Traverse the current vertex's neighbors

       

for

neighbor

in

graph

[

vertex

]

:

           

if

neighbor

not

in

visited:

                visited.

add

(

neighbor

)

                queue.

append

(

neighbor

)

   

return

result

Test Data

test_graph

=

{

   

'A'

:

[

'B'

,

'C'

]

,

   

'B'

:

[

'A'

,

'D'

,

'E'

]

,

   

'C'

:

[

'A'

,

'F'

]

,

   

'D'

:

[

'B'

]

,

   

'E'

:

[

'B'

,

'F'

]

,

   

'F'

:

[

'C'

,

'E'

]

}

print

(

"BFS traversal order (starting from A):"

,

bfs

(

test_graph

,

'A'

)

)

Possible output: ['A', 'B', 'C', 'D', 'E', 'F']

Depth-First Search

Depth-First Search (DFS) is like "walking through a maze": choose a path and follow it to the end, then backtrack and try another path. It usesStack(or recursion) to implement it.

Recursive algorithm steps:

  1. Starting from vertex v , mark it as visited.
  2. For v every unvisited neighbor of it u: a. recursively call DFS(u)。

Example

def

dfs_recursive

(

graph

,

vertex

,

visited

=

None

,

result

=

None

)

:

   

"""Implement DFS using recursion"""

   

if

visited

is

None

:

        visited

=

set

(

)

   

if

result

is

None

:

        result

=

[

]

    visited.

add

(

vertex

)

    result.

append

(

vertex

)

   

for

neighbor

in

graph

[

vertex

]

:

       

if

neighbor

not

in

visited:

            dfs_recursive

(

graph

,

neighbor

,

visited

,

result

)

   

return

result

print

(

"DFS traversal order (starting from A):"

,

dfs_recursive

(

test_graph

,

'A'

)

)

Possible output: ['A', 'B', 'D', 'E', 'F', 'C']

Comparison of Graph Traversal Algorithms:


Classic Applications and Algorithm Overview

Once you master graph representation and traversal, you can explore many classic problems:

  1. Shortest Path Problems: in map navigation, find the shortest driving distance between two points.

  2. Dijkstra's Algorithm: suitable fornon-negative weightsgraphs.
  3. Floyd's Algorithm: compute the shortest paths between all pairs of vertices.
  4. - **Dijkstra's Algorithm**: suitable for graphs with **non-negative weights**. - **Floyd's Algorithm**: computes shortest paths between all pairs of vertices.
    1. Minimum spanning tree: while keeping all vertices connected, choose the edge set with the minimum total weight (for example, laying the cheapest fiber-optic network for several villages).

    2. Prim's Algorithm
    3. Kruskal's Algorithm
    4. - **Prim's Algorithm** - **Kruskal's Algorithm**
      1. Topological sort: linearly order the vertices of a directed acyclic graph (DAG) so that for any directed edge u->v,u comes before v in the ordering (for example, arranging the order of courses).