I've been working on creating a bfs search algorithm on a 2D grid in Python (object-oriented). I have a Grid class that takes care of setting up the 2D grid and has some member functions to mark walls, start/end points, etc.
class Grid:
def __init__(self, nodes=[]):
self.nodes = nodes
# Initializes a grid of rl x rc and fills all nodes with and empty value of 1
def init_grid(self, rl, cl):
arr = []
arr2 = []
for i in range(rl):
for j in range(cl):
arr2.append(Node("1", i, j))
arr.append(arr2)
arr2 = []
self.nodes = arr
# Sets the start and end points at the specified rows and cols
def set_start_and_end(self, startr, startc, endr, endc):
startNode = Node("S", startr, startc)
endNode = Node("E", endr, endc)
self.nodes[startr][startc] = startNode
self.nodes[endr][endc] = endNode
def mark_visited(self, row, col):
self.nodes[row][col].val = "V"
def mark_wall(self, row, col):
self.nodes[row][col].val = "X"
I also have a file that will contain all my search algorithms (just BFS for now). In one of my helper functions for finding neighbours of a node, it takes in a node object as well as a grid object.
def get_neighbors(self, node, grid):
neighbours = []
R = len(grid)
C = len(grid[0])
dr = [-1, +1, 0, 0]
dc = [0, 0, +1, -1]
for i in range(4):
rr = node.r + dr[i]
cc = node.c + dc[i]
if rr < 0 or cc < 0: continue
if rr >= R or cc >= C: continue
neighbour = grid[rr][cc]
neighbours.append(neighbour)
return neighbours
I'm new to Python, and come from typecast languages, but is there a way to typecast my node and grid objects in some way? As of right now I don't need to instantiate either the grid or node objects, but I'm not sure how to access them otherwise. Unless I'm just going about this the wrong way.