[Python] How to make an adjacency matrix / adjacency list [Graph theory]

Introduction

When you're doing competitive programming, the wall you hit sooner or later is "graph theory." It is a problem related to (?) Graph theory that starts with breadth-first search and depth-first search and has infinite extent, but this time how to create "adjacency matrix" and "adjacency list" in Python I summarized about. It will be updated from time to time ...

Adjacency matrix and adjacency list

For example, consider the following graph. fig.png

There are two main types of graph data structures on a computer. Let's use it properly according to the situation. One is the adjacency matrix, which is in the form of a $ n \ times n $ matrix. It uses a lot of memory, but it has the advantage of being able to determine if there is a specific edge in a constant time.

adj_m.txt


[[0, 1, 1, 0, 1],
 [1, 0, 1, 1, 0],
 [1, 1, 0, 1, 1],
 [0, 0, 1, 1, 1],
 [1, 0, 1, 1, 0]]

The other is the adjacency list. Although it uses less memory, it has the disadvantage that it takes $ O (V) $ at worst to determine if there is a particular edge.

adj_l.txt


[[2, 3, 5], [1, 3, 4], [1, 2, 4, 5], [2, 3, 5], [1, 3, 4]]

The actual problem is that you are given a two endpoints of an edge, such as AtCoder Beginners Contest 168 D .. (Double Dots). There are many.

When I try to express the input for this graph, it becomes as follows. (The number of vertices n and the number of sides m are entered in the first line)

input.txt


5 8
1 2
1 3
1 5
2 3
2 4
3 4
3 5
4 5

code

I will write a cheat sheet that converts these into adjacency matrices and adjacency lists.

Input to adjacency matrix

When there is no weight

input_to_adj_m.py


n, m = map(int, input().split())
p = [list(map(int, input().split())) for _ in range(m)]

l = [[0]*n for i in range(n)]
for v in p:
    l[v[0]-1][v[1]-1] = 1
    l[v[1]-1][v[0]-1] = 1  #Erase if it is a directed graph

print(l)  # [[0, 1, 1, 0, 1], ..., [1, 0, 1, 1, 0]]

If there is weight, it will change slightly.

input_to_adj_m.py


n, m = map(int, input().split())
p = [list(map(int, input().split())) for _ in range(m)]

graph = [[0]*n for _ in range(n)]
for v in p:
    graph[v[0]-1][v[1]-1] = v[2]  #Here is changing
    graph[v[1]-1][v[0]-1] = v[2]  #Erase if it is a directed graph

print(graph)  # [[0, 1, 1, 0, 1], ..., [1, 0, 1, 0, 0]]

Input to adjacency list

input_to_adj_l.py


n, m = map(int, input().split())
p = [list(map(int, input().split())) for _ in range(m)]

graph = [[] for _ in range(n)]
for v in p:
    graph[v[0]-1].append(v[1])
    graph[v[1]-1].append(v[0])  #Erase if it is a directed graph

print(graph)  # [[2, 3, 5], ..., [1, 3, 4]]

in conclusion

Thank you for reading. I would be grateful if you could let me know if there are any mistakes or typographical errors.

Recommended Posts

[Python] How to make an adjacency matrix / adjacency list [Graph theory]
[Blender x Python] How to make an animation
[Python] How to use list 1
[Python] How to make a list of character strings character by character
How to make a Python package (written for an intern)
[Python] How to use list 3 Added
How to make a string into an array or an array into a string in Python
[Python] How to make a matrix of repeating patterns (repmat / tile)
[Python] How to make a class iterable
python3 How to install an external module
[Python] How to convert a 2D list to a 1D list
How to convert Python to an exe file
Summary of how to use Python list
How to make an embedded Linux device driver (11)
How to make an embedded Linux device driver (8)
How to clear tuples in a list (Python)
How to make an embedded Linux device driver (4)
How to make an embedded Linux device driver (7)
How to make an embedded Linux device driver (2)
How to crop an image with Python + OpenCV
How to make an embedded Linux device driver (3)
[Algorithm x Python] How to use the list
How to make an embedded Linux device driver (6)
How to make Substance Painter Python plugin (Introduction)
[Blender x Python] How to make vertex animation
How to make an embedded Linux device driver (5)
How to make an embedded Linux device driver (10)
How to make Python faster for beginners [numpy]
How to make Python Interpreter changes in Pycharm
How to make an embedded Linux device driver (9)
How to remove duplicate elements in Python3 list
Python + chatwork + google extension = How to make an easy and funny chat BOT
How to install Python
How to install python
How to use list []
[Python] How to remove duplicate values from the list
Explain in detail how to make sounds with python
[Blender x Python] How to create an original object
How to write a list / dictionary type of Python3
[Python] How to use the graph creation library Altair
How to make an interactive CLI tool in Golang
How to make a Python package using VS Code
[Python] How to sort dict in list and instance in list
How to make an HTTPS server with Go / Gin
[Python] I want to make a nested list a tuple
How to create an image uploader in Bottle (Python)
[Python] How to create Correlation Matrix and Heat Map
How to make an embedded Linux device driver (12) (Complete)
[Python] How to output the list values in order
How to install Python [Windows]
python3: How to use bottle (2)
[Python] Convert list to Pandas [Pandas]
How to convert an array to a dictionary with Python [Application]
How to swap elements in an array in Python, and how to reverse an array.
How to shuffle a part of a Python list (at random.shuffle)
How to update Python Tkinter to 8.6
[Python] How to write an if statement in one sentence.
How to use Python argparse
Python: How to use pydub
[Python] How to use checkio
How to get the last (last) value in a list in Python