Table of Contents
IronForgeCyber
Courses
Resources
Blog
Log In


IronForgeCyber

AboutPrivacyTerms

© 2026 IronForgeCyber. All rights reserved.

  1. courses
  2. python
  3. graphs
8 min read

Graph Theory

Python's networkx package is an extremely powerful tool for solving problems related to graph theory and other challenges. NetworkX is founded upon creating and manipulating a Graph object that contains many methods for processing the graph once it's built.

NetworkX is a third-party package, so install it into your project's environment first (see Packages & Environments):

$ uv add networkx

Building a Graph

Using the networkx.Graph() method, we can create a graph with zero nodes and edges.

python
1import networkx as nx
2
3g = nx.Graph()

NetworkX stores the graph using dictionaries, so a node can be any hashable object: a number, a string, a tuple such as an (x, y) grid coordinate, or an instance of your own class.

Nodes can be added in several ways. The standard methods for adding nodes are Graph.add_node(hashable) or Graph.add_nodes_from(container). Here are some examples of using each method:

python
1g.add_node(1)                   # adds node (1) with no edges
2g.add_nodes_from([2, 4, 5])     # adds three more nodes with no edges

Edges can be added one at a time or from a container. Using Graph.add_edge(start, end) or Graph.add_edges_from(tuple_container), we can add edges the same way we added nodes. Here are some examples:

python
1g.add_edge(1, 2)                      # edge now from 1-2
2g.add_edges_from([(1, 4), (2

After these additions, we can see that the graph has 11 nodes and 3 edges. Verify this by running len(g.edges) or g.number_of_edges():

python
1len(g)                 # Return: 11
2len(g.nodes)           # Return: 11
3g.number_of_nodes()    # Return: 11
Info
nx.Graph.edges and nx.Graph.nodes are of type nx.NodeView. These act like sets. They can be converted to lists using list(nx.NodeView).

Removing nodes and edges works the same way as adding them. Use methods Graph.remove_node(), Graph.remove_nodes_from(), Graph.remove_edge() and Graph.remove_edges_from(), e.g.

python
1g.remove_node(2)
2g.remove_nodes_from("string")

Graph Methods

There are too many methods to cover, but we will highlight some useful methods for common algorithms and popular challenge topics.

Shortest Path

Arguably the most useful method in the module, the nx.shortest_path(nx.Graph, start, end) method finds the shortest path between two points. The start and end parameters are the names of the nodes. Here is an example:

python
1import networkx as nx
2
3# make a graph
4g = nx.Graph()
5g.add_edges_from

Let's add another equally distant path. We can use nx.all_shortest_paths() to get a generator containing all shortest paths.

python
1# add another equally long path
2g.add_edges_from([(4, 6), (6, 7), (7

Articulation Points

An articulation point is a point at which, if removed, the graph would split into more than one disconnected component. networkx allows for the quick computation of articulation points. The nx.articulation_points(nx.Graph) method returns a generator object containing the articulation points. Using the list() method, we convert this to a list.

python
1import networkx as nx
2
3# make a graph
4g = nx.Graph()
5g.add_edges_from

Minimum Edge Cut

A similar problem asks for the smallest set of edges that, if removed, disconnects the graph into more than one component. Using nx.minimum_edge_cut(nx.Graph), we can compute this with ease. Here we use the graph from Shortest Path, which is a single loop of six nodes, so no one edge disconnects it but any two edges will:

python
1import networkx as nx
2
3# make a graph
4g = nx.Graph()
5g.
Warning
This method returns a set of edges that meets this criterion. Our loop has fifteen different two-edge cuts, and this method only yields one of them.

Connected Components

Now that we've found edges that cut the graph apart, we want to know which nodes ended up together. We can use nx.connected_components(nx.Graph) to do this, which returns a generator containing sets of connected nodes.

python
1# remove the minimum cut
2g.remove_edges_from(min_cut)
3
4# find the connected components
5comps = nx.connected_components(

The cut NetworkX picked happened to isolate node 6. A different two-edge cut, such as (2, 5) and (4, 6), would have split the loop evenly into {1, 2, 4} and {5, 6, 7}. When a problem guarantees there is exactly one minimum cut, as the challenge below does, this ambiguity goes away.

If we combine some of these, we can quickly solve a graph theory problem. Consider the Advent of Code 2023 Day 25 challenge. This challenge said to cut the 3 wires that split the electrical grid in 2, then find the product of the number of nodes in each connected component. Here's how we can do this using networkx:

python
1import networkx as nx
2from math import prod
3
4# add nodes from input
5G =

This instantly solved the challenge and earned 8th Place!

Printing Graphs

Printing a graph is the quickest way to check that you built what you meant to. The examples below use the six-node loop from Shortest Path:

python
1import networkx as nx
2
3g = nx.Graph()
4g.add_edges_from([(1, 2

Printing Graph Summary

We can use print(networkx.Graph) to get a summary of a graph.

python
print(g)    # Console: Graph with 6 nodes and 6 edges

The counts are a useful sanity check after parsing input, but they say nothing about the structure.

Printing as a Dictionary

Using the nx.to_dict_of_lists, we can return a dictionary containing the nodes and edges of the graph.

python
1>>> print(nx.to_dict_of_lists(g))
2{1: [2, 4], 2:

Nodes are shown as dictionary keys, and the values are the lists of the nodes that the node is connected to. Another method is nx.to_dict_of_dicts, which nests a dictionary of edge attributes under each neighbor. Our edges have no attributes, so those are empty:

python
1>>> print(nx.to_dict_of_dicts(g))
2{1: {2: {}, 4

Drawing the Graph

If we want to see the graph, we need another library: matplotlib, installed the same way as NetworkX. Matplotlib contains a sublibrary, matplotlib.pyplot, which allows for graph plotting. Without going into much detail about this library, below is an example of how it is used.

We use the nx.draw() method to illustrate the graph, with with_labels=True so each node shows its name:

python
1import networkx as nx
2import matplotlib.pyplot as plt
3
4nx.draw(g, with_labels=True)

nx-draw.webp

NetworkX places the nodes with a randomized layout, so your drawing will be arranged differently each time you run it. The nodes and edges are always the same.

3
4g.add_node("string") # adds node ("string")
5g.add_nodes_from("string") # adds 6 nodes ("s", "t", "r", "i", "n", "g")
,
5
)
]
)
# edges between 1-4 and 2-5
4len(g.edges) # Return: 3
5g.number_of_edges() # Return: 3
(
[
(
1
,
2
)
,
(
1
,
4
)
,
(
2
,
5
)
]
)
6
7# find the shortest path
8path = nx.shortest_path(g, 4, 5)
9print(path) # Console: [4, 1, 2, 5]
,
5
)
]
)
3
4# find all shortest paths
5paths = nx.all_shortest_paths(g, 4, 5)
6print(list(paths)) # Console: [[4, 1, 2, 5], [4, 6, 7, 5]]
(
[
(
1
,
2
)
,
(
1
,
4
)
,
(
2
,
5
)
]
)
6
7# find the articulation points
8art_pts = nx.articulation_points(g)
9print(list(art_pts)) # Console: [2, 1]
add_edges_from
(
[
(
1
,
2
)
,
(
1
,
4
)
,
(
2
,
5
)
]
)
6g.add_edges_from([(4, 6), (6, 7), (7, 5)])
7
8# find a minimum cut solution
9min_cut = nx.minimum_edge_cut(g)
10print(min_cut) # Console: {(4, 6), (7, 6)}
g
)
6print(list(comps)) # Console: [{1, 2, 4, 5, 7}, {6}]
nx
.
Graph
(
)
6for node, connections in data.items(): # data contains challenge input
7 for connection in connections:
8 G.add_edge(node, connection)
9
10# split the graph into two
11cuts = nx.minimum_edge_cut(G)
12G.remove_edges_from(cuts)
13
14# get the connected components
15comps = list(nx.connected_components(G))
16# product of number of nodes per component
17print(prod(len(comp) for comp in comps))
)
,
(
1
,
4
)
,
(
2
,
5
)
,
(
4
,
6
)
,
(
6
,
7
)
,
(
7
,
5
)
]
)
[
1
,
5
]
,
4
:
[
1
,
6
]
,
5
:
[
2
,
7
]
,
6
:
[
4
,
7
]
,
7
:
[
6
,
5
]
}
:
{
}
}
,
2
:
{
1
:
{
}
,
5
:
{
}
}
,
4
:
{
1
:
{
}
,
6
:
{
}
}
,
5
:
{
2
:
{
}
,
7
:
{
}
}
,
6
:
{
4
:
{
}
,
7
:
{
}
}
,
7
:
{
6
:
{
}
,
5
:
{
}
}
}
5
plt
.
show
(
)