python - 网格中的图形深度优先搜索 (DFS)
问题描述
问题
有 n x n 网格,您必须从第 0 行第 0 列(左上角)开始我想知道探索网格所有隔间的路线数,并且不要通过已经搜索过的隔间。示例:n = 2 → 2 条路径
def dfs(size, cur_pos, route : list):
# size : size of grid, cur_pos : (current_row, current_column). each_row/col starts at 0
# route : list consists of positions so far. ex) [(0,0),(1,0),(1,1)]
route.append(cur_pos)
# append current position at route list first
# escape condition
if len(route) == pow(size, 2): # if length of route is same as the size of the grid
result_list.append(route) # add 1 to the number of path
return
to_move = [(1,0),(-1,0),(0,1),(0,-1)] # amount to move. down/up/right/left
for i in range(4):
next_pos = (cur_pos[0] + to_move[i][0], cur_pos[1] + to_move[i][1])
# set next position
if 0 <= next_pos[0] < size and 0 <= next_pos[1] < size: # if next position is still in the grid
if next_pos not in route: # if next position is not already searched
dfs(size, next_pos, route) # search recursively
result_list = [] # save each complete routes
input_size = int(input())
dfs(input_size, (0,0), [])
print(len(result_list)) # always print 1....
这段代码总是打印 1...
我认为route
每次搜索完成时变量似乎都没有被清除,但我不知道如何解决这个问题。有谁知道如何让它做到这一点?
解决方案
推荐阅读
- sql - Postgres OFFSET 子查询分组的结果
- mysql - 真的很长的mysql查询然后真的很快
- javascript - 将 mapbox-map-matching API 与 react 集成 - 限制路由选项
- json - 在 Go 中解析具有兄弟动态键和静态键的 JSON
- c++ - 正则表达式 - 在单独的捕获组中捕获每个参数:[cmd arg1 arg2 arg3...]
- google-cloud-platform - Colab / Google Cloud SDK - 本地运行时总是“忙” - 无法重新启动
- javascript - 如何确保当您单击其中一个箭头时,您会转到下一部分或上一部分?
- python - 在 PyQt5(Python)中将小部件(QCheckBox)添加到 QFileDialog 不起作用
- c# - 为什么VS2019还在把嵌入的资源复制到输出文件夹?
- javascript - 即使在配额扩展获得批准后,Spotify API 也不会向人们提供访问权限