Adjacency Matrix Class

Question:

I was wondering how to create a method that would return a list of neighbors of vertex u and also a method that returns true if two vertices are adjacent to each other in a matrix. I also wanted to know if I was setting up my matrix correctly. I saw a solution for an adjacency list but I think the setup for a matrix is different

Here is my class so far:

Class AdjMatrix():

    # Initialize the matrix
    def __init__(self):
        self.adjMatrix = []

    # Add edges
    def add_edge(self, u, v):
        if u == v:
            print("Same vertex u and v")
        self.adjMatrix[u][v] = 1
        self.adjMatrix[u][v] = 1

    # Remove edges
    def remove_edge(self, u, v):
        if self.adjMatrix[u][v] == 0:
            print("No edge between %d and %d" % (u, v))
            return
        self.adjMatrix[u][v] = 0
        self.adjMatrix[v][u] = 0

    def __len__(self):
        return self.size

    # Print the matrix
    def print_matrix(self):
        for row in self.adjMatrix:
            for val in row:
                print('{:4}'.format(val)),
            print

I was not really sure where to begin so any help would be much appreciated 😀

Asked By: Vincent Yang

||

Answers:

I feel I basically just answered this; (Did flag as dup)

Creating an adjacency list class in Python

   class Matrix:
    def __init__(self, size):
        self.matrix = [[0 for x in range(size)] for y in range(size)]

    def addEdge(self, u, v):
        self.matrix[u][v] = 1

    def deleteEdge(self, u, v):
        self.matrix[u][v] = 0

    def getNeighbors(self, u):
        neighbors = []
        for i in range(len(self.matrix[u])):
            if self.matrix[u][i] == 1:
                neighbors.append(i)
        return neighbors

    def isAdjacent(self, u, v):
        if self.matrix[u][v] == 1:
            return True
        else:
            return False

    def printMatrix(self):
        for i in range(len(self.matrix)):
            print(self.matrix[i])
            
m = Matrix(5)
m.addEdge(0, 1)
m.addEdge(0, 4)
m.addEdge(1, 0)
m.addEdge(1, 2)
m.addEdge(1, 3)
m.addEdge(1, 4)
m.addEdge(2, 1)
m.addEdge(2, 3)
m.addEdge(3, 1)
m.addEdge(3, 2)
m.addEdge(3, 4)
m.addEdge(4, 0)
m.addEdge(4, 1)
m.addEdge(4, 3)

m.printMatrix()
print(m.getNeighbors(1))
print(m.isAdjacent(1, 3))

Output:

[0, 1, 0, 0, 1]
[1, 0, 1, 1, 1]
[0, 1, 0, 1, 0]
[0, 1, 1, 0, 1]
[1, 1, 0, 1, 0]
[0, 2, 3, 4]
True

EDIT: Refactored to output matrix

Answered By: Madison Courto
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.