簡體   English   中英

有障礙物的 DFS 尋路

[英]DFS path finding with obstacles

我有以下網格,我正在嘗試到達該網格中的 1,障礙物顯示為 2。機器人按以下順序優先移動:向上、向右、向下、向左。 起始位置旁邊有一個 *。

 0   0*  0
 0   2   0
 1   1   0

到目前為止,我所做的是將該網格的位置放入圖形形式中,並按照優先順序從每個位置生成所有可能的移動。 但我的問題是算法在到達第二行的最后一部分時陷入循環。 我正在嘗試實現某種循環檢測器,這樣我就不會陷入該循環中。

我還應該提到,只要機器人通過不同的路徑,它就可以兩次訪問同一位置。 所以到目前為止我所擁有的是:

def dfs(grid,start):

    #find the routes in U,R,D,L order
    height = len(grid)

    width = len(grid[0])

    routes = {(i, j) : [] for j in range(width) for i in range(height)}

    for row, col in routes.keys():
      # Left moves
     if col > 0: 
          routes[(row, col)].append((row , col - 1))
      # Down moves    
     if row < height - 1:
          routes[(row, col)].append(((row + 1, col)))
     # Right moves
     if col < width - 1: 
         routes[(row, col)].append(((row , col + 1)))
     # Up moves
     if row > 0:
         routes[(row, col)].append(((row - 1, col)))

  #find the blocked ones

   blocked = {(i,j) for j in range(width) for i in range(height) if grid[i][j] == 2}

   path = []

   stack = [start]

   while stack:
     node = stack.pop()

     if node not in blocked:
         path.append(node)
         stack = []
         for x in routes[node]:
             stack.extend([x])

  return path

在哪里

 grid = [[0, 0, 0], [0, 2, 0], [1, 1, 0]]
 start = (0,1)

手動執行此操作表明路徑應如下所示:右、下、下、左、右、上、上、左、左、下、下

關於如何實現檢測器的任何建議都會很棒,我對 AI 和 python 很陌生,我一整天都在試圖解決這個問題……謝謝

嘗試這個:

def dfs2(grid,pos,curr,height,width):
    x = pos[0]
    y = pos[1]    
    if grid[x][y]==1:
        print str(curr)
        return None
    elif grid[x][y] ==2:
        return None        
    last = curr[-1]    
    if x-1 >= 0 and last != 'DOWN':        
        curr.append('UP')
        dfs2(grid,(x-1,y),curr,height,width)
        curr.pop()
    if y+1 < width and last != 'LEFT':        
        curr.append('RIGHT')
        dfs2(grid,(x,y+1),curr,height,width)
        curr.pop()
    if x+1 < height and last != 'UP':
        curr.append('DOWN')
        dfs2(grid,(x+1,y),curr,height,width)
        curr.pop()
    if y-1>=0 and last != 'RIGHT':
        curr.append('LEFT')
        dfs2(grid,(x,y-1),curr,height,width)
        curr.pop()


def dfs(grid,pos):
    dfs2(grid,pos,['START'],len(grid),len(grid[0]))

########MAIN#########
#up, right, down, left
grid = [[0, 0, 0], [0, 2, 0], [1, 1, 0]]
start = (0,1)
print str(grid)
dfs(grid,start)

這是基於遞歸的。 嘗試根據問題中指定的順序移動到下一個位置,並將移動存儲在到達目的地時打印的列表中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM