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 networkxUsing the networkx.Graph() method, we can create a graph with zero nodes and edges.
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:
1g.add_node(1) # adds node (1) with no edges
2g.add_nodes_from([2, 4, 5]) # adds three more nodes with no edgesEdges 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:
1g.add_edge(1, 2) # edge now from 1-2
2g.add_edges_from([(1, 4), (2After 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():
1len(g) # Return: 11
2len(g.nodes) # Return: 11
3g.number_of_nodes() # Return: 11nx.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.
1g.remove_node(2)
2g.remove_nodes_from("string")There are too many methods to cover, but we will highlight some useful methods for common algorithms and popular challenge topics.
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:
1import networkx as nx
2
3# make a graph
4g = nx.Graph()
5g.add_edges_fromLet's add another equally distant path. We can use nx.all_shortest_paths() to get a generator containing all shortest paths.
1# add another equally long path
2g.add_edges_from([(4, 6), (6, 7), (7An 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.
1import networkx as nx
2
3# make a graph
4g = nx.Graph()
5g.add_edges_fromA 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:
1import networkx as nx
2
3# make a graph
4g = nx.Graph()
5g.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.
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:
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 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:
1import networkx as nx
2
3g = nx.Graph()
4g.add_edges_from([(1, 2We can use print(networkx.Graph) to get a summary of a graph.
print(g) # Console: Graph with 6 nodes and 6 edgesThe counts are a useful sanity check after parsing input, but they say nothing about the structure.
Using the nx.to_dict_of_lists, we can return a dictionary containing the nodes and edges of the graph.
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:
1>>> print(nx.to_dict_of_dicts(g))
2{1: {2: {}, 4If 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:
1import networkx as nx
2import matplotlib.pyplot as plt
3
4nx.draw(g, with_labels=True)

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.