0

I am trying to make my own representation of Dijkstra's algorithm in python using Pygame for visuals (Not implemented yet). I have a function that generates a dictionary of nodes with their positions on the grid. In that function, there is a for loop that assigns every node their neighbors via a dictionary stored in the node. Yet, when I run it, I see that every 'neighbor' for every node has also been assigned to all the other nodes. I have wracked my brain but I can't seem to figure out the problem.

Here is the code: (I apologize for any unclear code as I am relatively new and this is kind of only a part of the whole code)

class Node: #NODE CLASS
    def __init__(self, name, pos, conn_nodes={}):
        self.connected_nodes = conn_nodes
        self.parent = None
        self.estimate = None
        self.explored = False
        self.name = name
        self.pos = pos
    
    def __repr__(self):
        return(f"Node: {self.name}")
        
        
def generateNodes():
    nodes = {}
    for x in range(SquaresX):
        for y in range(SquaresY):
            nodes[(x, y)] = Node((x, y), (x, y))
    
    for n in nodes.values(): # THE PROBLEM FOR LOOP
        if n.pos[0] != 0: #check if on the left edge
            connNode = nodes[(n.pos[0]-1, n.pos[1])]
            n.connected_nodes[connNode] = 1 
            
        if n.pos[0] != SquaresX-1: #check if on the right edge
            connNode = nodes[(n.pos[0]+1, n.pos[1])]
            n.connected_nodes[connNode] = 1
            
        if n.pos[1] != 0: #check if on the top edge
            connNode = nodes[(n.pos[0], n.pos[1]-1)]
            n.connected_nodes[connNode] = 1
            
        if n.pos[1] != SquaresY-1: #check if on the bottom edge
            connNode = nodes[(n.pos[0], n.pos[1]+1)]
            n.connected_nodes[connNode] = 1
    
    return nodes


SquaresX = 20
SquaresY = 20

nodes = generateNodes()
print(nodes[(0, 0)]) # i expect this to print a dictionary with 2 keys/neighbors (top left of the #grid) but instead it basically lists out all of the other neighbors including the right ones

I tried putting print statements every where but all the neighbors just seems to some how jump to every single other node in the dictionary. I expected there to be 2-4 neighbors per node depending on their placement on the grid.

  • As the duplicate will hopefully explain, the issue with your code is `conn_nodes={}`. Since the dictionary you're using as the default is mutable (and you go on to modify it later), it's problematic to use it as a default argument because it will be shared by all nodes (that don't get a dictionary passed in). Since you don't seem to ever pass a dict in, you could just get rid of it as an argument, and do `self.connected_nodes = {}` instead. – Blckknght Mar 16 '23 at 21:35

0 Answers0