使用BFS

时间:2016-06-12 08:21:06

标签: algorithm shortest-path breadth-first-search

尝试使用BFS解决this problem

问题要点:给出放置在矩阵中的rook的初始和最终位置。您需要找出车辆到达最终位置的最小步数。某些位置标有" X"不应该被交叉,而"。"是允许的职位。

Matrix:
.X.
.X.
...
source position: 0,0
target position: 0,2
answer:3 (0,0) -> (2,0) - > (2,2) -> (0,2)

我的解决方案基本上如下: 我从源节点开始做BFS,在我将节点出列后,我将内存中的所有垂直和水平节点添加到该节点的当前距离加上1.然后我检查目标节点是否存在于内存中以及是否存在我在回来那段距离。

以下解决方案在某些情况下无效。有什么建议吗?

def update_distance(memoize_dist, current, n, count, matrix):
  directions = [1, -1, 1, -1]
  current_x, current_y = current
  temp_x, temp_y = current
  for direction in directions:
    while temp_x < n and temp_x >= 0:
      temp_x += direction
      temp = (temp_x, current_y)    
      if temp_x >= n or temp_x < 0 or matrix[temp_x][current_y] == 'X':
        temp_x, temp_y = (current_x, current_y)
        break                   
      if temp not in memoize_dist.keys():
        memoize_dist[temp] = count
  for direction in directions:
    while temp_y < n and temp_y >= 0:
      temp_y += direction
      temp = (current_x, temp_y)
      if temp_y >= n or temp_y < 0 or matrix[current_x][temp_y] == 'X':
        temp_x, temp_y = (current_x, current_y)
        break       
      if temp not in memoize_dist.keys():               
        memoize_dist[temp] = count

def get_shortest(n, src, target, matrix):
    queue, memoize, memoize_dist = [], {}, {}
    queue.append((src[0], src[1], 0))
    memoize_dist[(src[0], src[1])] = 0
    while len(queue):
      x, y, count = queue.pop(0)
      cur = (x, y)
      if cur in memoize.keys() and memoize[cur] != -1:
        continue
      memoize[cur] = 1          
      update_distance(memoize_dist, cur, n, count+1, matrix)    
      if target in memoize_dist.keys():
        return memoize_dist[target]
      directions = [1, -1, 1, -1]
      for direction in directions:
        if cur[0]+direction < n and cur[0]+direction >= 0 and matrix[cur[0]+direction][cur[1]] != 'X':
          queue.append((cur[0]+direction, cur[1], memoize_dist[(cur[0]+direction, cur[1])]))
        if cur[1]+direction < n and cur[1]+direction >= 0 and matrix[cur[0]][cur[1]+direction] != 'X':
          queue.append((cur[0], cur[1]+direction, memoize_dist[(cur[0], cur[1]+direction)]))

n = int(input())
matrix = []
for i in range(n):
    matrix.append(input())
start_x, start_y, dest_x, dest_y = map(int, input().split(" "))
print(get_shortest(n, (start_x, start_y), (dest_x, dest_y), matrix))

0 个答案:

没有答案