简体   繁体   English

Python 迷宫最短路径上的 BFS 搜索无法解决,我正在尝试执行广度优先搜索,以查找在网格中具有 4 次移动的代理

[英]Python BFS search on maze shortest path unable to solve, am trying to perform a breadth first search for an agent that has 4 moves across the grid

I am trying to perform a breadth first search for an agent that has 4 moves across the grid that is read in through a text file.我正在尝试对通过文本文件读取的网格中具有 4 次移动的代理执行广度优先搜索。 I cannot get it to run for some reason.由于某种原因,我无法让它运行。 although I follow the algorithm as in my textbook.尽管我遵循教科书中的算法。 I am new to coding and any help would be appreciated.我是编码新手,任何帮助将不胜感激。 This is my first Stack Overflow post, its nice to join you folks:) Please don't roast me:( edit** the text is in a file and is something like this: 3 0 0 0 0 1 0 0 3 3 3 0 3 0 0 0 0 0 3 3 3 0 3 0 0 0 0 0 3 3 3 0 3 0 0 0 0 0 3 3 3 0 3 0 0 0 0 0 3 3 3 0 3 0 0 0 0 2 3 3 3 0 3 0 0 0 0 3 3 3 3 0 3 0 0 0 0 3 3 3 3 0 3 2 2 0 0 3 3 3 3 3 3 3 3 2 0 3 3 3. edit**It is presently crashing and I do not understand how to fix the errors as every error I fix causes more errors to appear, I simply want to get it to display the output of moves in a sequence of 'Move Up', 'Move Down' etc.这是我的第一篇 Stack Overflow 帖子,很高兴加入你们的行列:) 请不要烤我:( 编辑**文本在一个文件中,是这样的:3 0 0 0 0 1 0 0 3 3 3 0 3 0 0 0 0 0 3 3 3 0 3 0 0 0 0 0 3 3 3 0 3 0 0 0 0 0 3 3 3 0 3 0 0 0 0 0 3 3 3 0 3 0 0 0 0 2 3 3 3 0 3 0 0 0 0 3 3 3 3 0 3 0 0 0 0 3 3 3 3 0 3 2 2 0 0 3 3 3 3 3 3 3 3 2 0 3 3 3. 编辑**它目前正在崩溃,我愿意不明白如何修复错误,因为我修复的每个错误都会导致出现更多错误,我只是想让它以“上移”、“下移”等顺序显示移动的 output。

import collections

    def read_user_input():
        file_name = input('Enter the name of your file :\n')
        return file_name
    
    
    def read_to_grid():
        file_name = read_user_input()
        for nums in open(file_name):
            line = list(nums.split())
            result = []
            for _ in range(0, len(line), 10):
                result.append(line[_:_ + 10])
            print(result)
            return result
        file_name.close()
    
    
    def grid_start_position():
        grid = read_to_grid()
        for x, pos in enumerate(grid[0]):
            if pos == "O":
                start = x
                return start
    
    
    def bfs():
        grid = read_to_grid()
        start = grid_start_position()
        queue = collections.deque([[start]])
        seen = set([start])
        while queue:
            path = queue.popleft()
            path_moves = ''
            x, y = path[-1]
            if grid[y][x] == '2':
                return path
            for x2, y2 in (x + 1, y):
                if 0 <= x2 < 10 and 0 <= y2 < 10 and grid[x2][y2] != '3' and (x2, y2) not in seen:
                    queue.append(path + [(x2, y2)])
                    path_moves = path_moves + 'Move Up '
                    seen.add((x2, y2))
            for x2, y2 in (x - 1, y):
                if 0 <= x2 < 10 and 0 <= y2 < 10 and grid[x2][y2] != '3' and (x2, y2) not in seen:
                    queue.append(path + [(x2, y2)])
                    path_moves = path_moves + 'Move Down '
                    seen.add((x2, y2))
            for x2, y2 in (x, y + 1):
                if 0 <= x2 < 10 and 0 <= y2 < 10 and grid[x2][y2] != '3' and (x2, y2) not in seen:
                    queue.append(path + [(x2, y2)])
                    path_moves = path_moves + 'Move Right'
                    seen.add((x2, y2))
            for x2, y2 in (x, y - 1):
                if 0 <= x2 < 10 and 0 <= y2 < 10 and grid[x2][y2] != '3' and (x2, y2) not in seen:
                    queue.append(path + [(x2, y2)])
                    path_moves = path_moves + 'Move Left'
                    seen.add((x2, y2))
    
            print(path_moves)
    
    
    bfs()

Some issues:一些问题:

  • grid_start_position only returns an x-coordinate, and you put that start in the queue, yet in the loop you expect the queue to have coordinate- pairs (x and y). grid_start_position只返回一个 x 坐标,你把它放在队列中,但start循环中你希望队列有坐标(x 和 y)。 You should better update grid_start_position to return an x, y pair.您最好更新grid_start_position以返回 x, y 对。 NB: it may need an extra loop on the y-coordinate, as you can not be sure that the start is always on the first line?注意:在 y 坐标上可能需要一个额外的循环,因为你不能确定起点总是在第一行?

  • There is a if pos == "O" condition there, that is never true, as the input you provided only has numeric data, so no letter "O".那里有一个if pos == "O"条件,这绝不是真的,因为您提供的输入只有数字数据,所以没有字母“O”。 This should probably be a "0" (zero).这应该是一个“0”(零)。

  • You call read_to_grid() twice: once in bfs and then again in grid_start_position .您调用read_to_grid()两次:一次在bfs中,然后再次在grid_start_position中。 Instead you should pass the grid in the call to grid_start_position .相反,您应该在对grid_start_position的调用中传递网格。

  • for x2, y2 in (x + 1, y) will not work. for x2, y2 in (x + 1, y)将不起作用。 You could say x2, y2 = (x + 1, y) , but your in operator will try to unpack x + 1 into two values.您可以说x2, y2 = (x + 1, y) ,但您的in运算符会尝试将x + 1解压缩为两个值。 In order to avoid the code repetition you have, you should probably make a loop like this:为了避免你的代码重复,你应该做一个这样的循环:

     for move, x2, y2 in (("Right", x + 1, y), ("Left", x - 1, y), ("Up", x, y - 1), ("Down", x, y + 1)):
  • With path_moves = path_moves + "some string" you keep adding all nodes you are visiting to that path, which makes no sense: this is not a path at all.使用path_moves = path_moves + "some string"您可以不断将您正在访问的所有节点添加到该路径,这没有任何意义:这根本不是一条路径。 You need a different technique, where you keep back-references ("where I came from") for each of the nodes that you visit.您需要一种不同的技术,为您访问的每个节点保留反向引用(“我来自哪里”)。 Then when you arrive at the target, you should (only then.) reconstruct the path from that information.然后,当您到达目标时,您应该(仅在那时)根据该信息重建路径。

I will not provide the corrected code, as this has been solved many times before.我不会提供更正的代码,因为这已经解决了很多次了。 You can for instance take inspiration from How do I find shortest path in maze with BFS?例如,您可以从How do I find shortest path in maze with BFS? 中获得灵感? , where the OP had a similar issue with building the path. ,其中 OP 在构建路径时遇到了类似的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM