我一直在努力在Python(面向对象)的2D网格上创建bfs搜索算法。我有一个Grid类,负责设置2D网格,并具有一些标记墙,起点/终点等的成员函数。
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"
我还有一个包含所有搜索算法的文件(目前仅是BFS)。在我的一个用于查找节点邻居的辅助函数中,它包含一个节点对象以及一个网格对象。
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
我是Python的新手,来自类型转换语言,但是是否可以通过某种方式来类型化节点和网格对象?到目前为止,我不需要实例化网格或节点对象,但是我不确定如何访问它们。除非我只是以错误的方式来做。
网格类的功能取决于self,因此您必须立即实例化访问。 如果要静态行为,只需将类属性放在构造函数之外:
Then in your other file
from filename import Grid
and you should be able to access the static method withGrid.init_grid()
and access nodes withGrid.nodes
If you can't, you can get an "static" object withg_type = eval("Grid")
then you can access your "static" members withg_type.init_grid()
希望能有所帮助。