Понимание алгоритма поиска в ширину python - PullRequest
0 голосов
/ 06 марта 2020

Я пытаюсь понять эту реализацию поиска в ширину python, и я понимаю, что большинство из них показано в моих комментариях, но я не вижу здесь этой строки:

for dx, dy in [(-1, 0), (0, +1), (+1, 0), (0, -1)]:
           a, b = current[0] + dx, current[1] + dy #Start searching in a random direction

           if maze.in_maze(a, b) and not maze.is_wall(a, b) and (a, b) not in parent: #Check to see if the coordinates that are searching is inside the wall is not a wall and not inside of parent
               parent[(a, b)] = current #?
               dist[(a, b)] = dist[current] + 1; #?
               queue.append((a, b)) #Add the coordinates to the end of the queue

Весь код может найти здесь, пожалуйста, не стесняйтесь звонить мне по любой комментирующей ошибке. Я все еще новичок в python, поэтому я не знаю точно, что делает каждая строка, но я получаю грубое представление.

from collections import deque #A double-ended queue, or deque, supports adding and removing elements from either end. Import this from collections

nodes = 0 #Initialise nodes with value 0


def solve(maze, start, end): #Solve function that takes in the maze, start and end points as arguments
   global nodes #Declare nodes as a global variable
   nodes = 0 #Set nodes value to 0

   queue = deque() #Set queue as a double ended queue
   parent, dist = dict(), dict() #Set parent and dist

   queue.append(start) #Add start point to the queue
   parent[start], dist[start] = start, 1

   while len(queue): #While there are items in the list
       current = queue.popleft() #Set current to the first thing in the queue from the left
       nodes += 1 #Increment nodes by 1

       if current == end: #If the current place is the end target then solution has been found and we can exit the loop
           break #Exit the loop

       for dx, dy in [(-1, 0), (0, +1), (+1, 0), (0, -1)]:
           a, b = current[0] + dx, current[1] + dy #Start searching in a random direction

           if maze.in_maze(a, b) and not maze.is_wall(a, b) and (a, b) not in parent: #Check to see if the coordinates that are searching is inside the wall is not a wall and not inside of parent
               parent[(a, b)] = current #Set later
               dist[(a, b)] = dist[current] + 1; #set later
               queue.append((a, b)) #Add the coordinates to the end of the queue

   if end not in parent: #If there is no solution
      return [] #Return an empty solution
   else: #Otherwise if there is a solution
      path = [] #Initialise path as an empty list
      while start != end: #While the starting point is not the end point, the solution has not be found so
          path.append(end) #Keep appending the end node to the path queue until they meet the condition
          end = parent[end] #Set end point to the position it is in the parent dictionary
      path.append(start) #Insert the starting point to the end of the queue
      path.reverse() #Reverse the path queue since the solution was found back to front
      return path #Return the final solution

Ответы [ 2 ]

1 голос
/ 06 марта 2020

Итак, в приведенном выше коде после прочтения я предполагаю, что начало и конец представлены такими координатами, как (x, y). Кроме того, если вы выбираете любую координату в «лабиринте», вы можете перемещаться только в направлениях вверх, вниз, влево, вправо, т.е. если вы находитесь в координатах (x, y), вы можете только go к одной из следующих координат : (x + 1, y), (x-1, y), (x, y + 1), (x, y-1)

В общем, for l oop используется для выбора соседних координат, по которым вы можете перемещаться одна за другой. Затем a, b = current[0] + dx, current[1] + dy эта линия используется для получения абсолютных координат соседних координат. Затем мы проверяем, существует ли новая координата в лабиринте или это стена. Если он находится в лабиринте, а не в стене, а также мы еще не прошли через него, мы обновляем parent dict, а также обновляем dist dict (для расстояния).

* parent dict хранит родителя координаты. Таким образом, для (x+1, y) родитель будет (x, y), который является текущим. parent[(x+1, y)] = (x, y), что означает, что родительский элемент (x+1, y) равен (x, y)

, а dist dict хранит расстояние или число шагов, необходимых для достижения новой координаты. dist[(x+1, y)] = dist[(x,y)] + 1 это означает, что расстояние новой координаты равно расстоянию родительского + 1 нового шага.

Затем мы добавляем его в очередь.

1 голос
/ 06 марта 2020
parent[(a, b)] = current

используется для хранения координат (current) местоположения , из которого вы пришли к координатам (a, b). Да, и кстати, этот комментарий здесь неправильный:

   for dx, dy in [(-1, 0), (0, +1), (+1, 0), (0, -1)]:
       a, b = current[0] + dx, current[1] + dy #Start searching in a random direction

Это должно быть "Поиск в в каждом направлении, по одному за раз". Здесь нет ничего случайного.

...