Skip to content

Instantly share code, notes, and snippets.

@Parihsz
Created January 27, 2024 01:54
Show Gist options
  • Select an option

  • Save Parihsz/f204e038a3dc36b362cf6da4dc5770ef to your computer and use it in GitHub Desktop.

Select an option

Save Parihsz/f204e038a3dc36b362cf6da4dc5770ef to your computer and use it in GitHub Desktop.
Adjacency matrix implementations

Adjacency matrix implementations

2d list implementation

class adjacency_matrix_1:
    def __init__(self, N):
        self.matrix = [[False for _ in range(N)] * N]
    def connect(self, a, b, bidirectional=True):
        self.matrix[a][b] = True
        if bidirectional:
            self.matrix[b][a] = True
    def is_connected(self, a, b):
        return self.matrix[a][b]

Adjacency matrix dictionary

class adjacency_matrix_1:
    def __init__(self, N):
        self.matrix = set()
    def connect(self, a, b, bidirectional=True):
        self.matrix.add((a, b))
        if bidirectional:
            self.matrix.add((b, a))
    def is_connected(self, a, b):
        return (a, b) in self.matrix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment