Last active
February 13, 2020 06:16
-
-
Save Lugriz/e85369722a73d72bdb95b0f237f5e27d to your computer and use it in GitHub Desktop.
Prints each vertex with its levels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
PRINT GRAPH WITH LEVEL | |
""" | |
from queue import Queue | |
# Defining vertex class | |
class Vertex(): | |
def __init__(self, value): | |
self.value = value | |
self.neighbors = [] | |
# Creating vertex | |
vertex1 = Vertex(1) | |
vertex2 = Vertex(2) | |
vertex3 = Vertex(3) | |
vertex4 = Vertex(4) | |
vertex5 = Vertex(5) | |
vertex6 = Vertex(6) | |
vertex7 = Vertex(7) | |
vertex8 = Vertex(8) | |
vertex1.neighbors.append(vertex2) | |
vertex1.neighbors.append(vertex3) | |
vertex1.neighbors.append(vertex4) | |
vertex2.neighbors.append(vertex5) | |
vertex4.neighbors.append(vertex6) | |
vertex4.neighbors.append(vertex7) | |
vertex5.neighbors.append(vertex8) | |
# 1 | |
# / | \ | |
# 2 3 4 | |
# / / \ | |
# 5 6 7 | |
# / | |
# 8 | |
# Solution using tuples | |
def printGraphWithLevel(vertex): | |
collected = Queue() | |
collected.put((vertex, 1)) | |
while not collected.empty(): | |
vtx, level = collected.get() | |
print(vtx.value, ' level ', level) | |
level += 1 | |
for neighbor in vtx.neighbors: | |
collected.put((neighbor, level)) | |
printGraphWithLevel(vertex1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment