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.