maze_python/SourceCollector.py
2025-06-26 21:38:30 +08:00

144 lines
4.1 KiB
Python

import csv
class TreeNode:
def __init__(self):
self.fa = None
self.children = []
self.pos = None
self.val = 0
self.id = 0
self.dp = 0
self.path = []
self.dp_path = []
class SourceCollector:
def __init__(self, filename, maze=None):
self.filename = filename
self.maze = maze
self.start_pos = None
self.end_pos = None
self.path = []
if self.filename:
self.maze = []
with open(f"{self.filename}",'r') as f:
reader = csv.reader(f)
for row in reader:
t = []
for i in row:
if i.startswith('b') or i.startswith('l'):
t.append('0')
else:
t.append(i)
self.maze.append(t)
self.rowNums = len(self.maze)
self.colNums = len(self.maze[0])
for i in range(self.rowNums):
for j in range(self.colNums):
if self.maze[i][j] =='s':
self.start_pos = (i,j)
if self.maze[i][j] =='e':
self.end_pos = (i,j)
def dfs_show(self,u):
if u.id != 0:
print(f"id: {u.id} , fa:{u.fa.id} , val:{u.val}")
else:
print(f"id: {u.id} , val:{u.val}")
print(u.path)
for child in u.children:
self.dfs_show(child)
def outofmap(self,x,y):
return x < 0 or y < 0 or x > self.rowNums or y > self.colNums
def build_a_tree(self):
sn = TreeNode()
sn.pos = self.start_pos
id = 0
sn.id = id
sn.val = 0
sn.path = [sn.pos]
st = [[False] * self.colNums for _ in range(self.rowNums)]
qsk = []
sx, sy = self.start_pos
st[sx][sy] = True
qsk.append((self.start_pos[0],self.start_pos[1], sn,[]))
dx = [-1,0,1,0]
dy = [0,-1,0,1]
while qsk:
x, y, u,path = qsk.pop()
for _x, _y in zip(dx,dy):
nx, ny = x + _x, y + _y
if self.outofmap(nx,ny):
continue
if self.maze[nx][ny] == '1' or st[nx][ny]:
continue
st[nx][ny] = True
to = self.maze[nx][ny]
new_path = path + [(nx,ny)]
if to.startswith('g') or to.startswith('t'):
new_node = TreeNode()
id+=1
new_node.id = id
new_node.pos = (nx, ny)
new_node.fa = u
num_str = to[1:]
new_node.path = new_path
try:
if to.startswith('g'):
new_node.val = int(num_str)
else:
new_node.val = -int(num_str)
except ValueError:
print("wa ! ")
u.children.append(new_node)
qsk.append((nx, ny, new_node,[]))
else:
qsk.append((nx, ny, u,new_path))
return sn
def dfs(self,sn):
sn.dp = sn.val
for child in sn.children:
# print(f"cur : {child.pos} , fa : {child.fa.pos} , childrens : {child.path}")
self.dfs(child)
if child.dp > 0:
sn.dp += child.dp
sn.dp_path += child.path + child.dp_path + child.path[::-1]
def find_path(self):
self.path = []
sn = self.build_a_tree()
self.dfs(sn)
return self.path
if __name__ == '__main__':
obj = SourceCollector(filename="maze.csv")
sn = obj.build_a_tree()
# obj.dfs_show(sn)
obj.dfs(sn)
print(len(sn.dp_path))
print(sn.pos)
pre = sn.pos
for _ in sn.dp_path:
dx,dy = _[0] - pre[0],_[1]-pre[1]
if dx > 0:
print("down")
elif dx < 0:
print("up")
elif dy > 0:
print("right")
elif dy < 0:
print("left")
pre = _