最短路径算法 - 具有不可访问单元的矩阵

时间:2013-08-13 04:55:06

标签: algorithm

我在接受采访时被问到这个问题。我不知道该怎么做。 基本上我有一个布尔矩阵 - 其中0代表一个单元格无法访问。给定开始和目标单元格,如何构建从开始到目标的最短路径,而不跳过任何不可访问的单元格。你可以四个方向旅行。

由于

3 个答案:

答案 0 :(得分:1)

您需要使用面包优先搜索。从这个矩形板调制图形。

主要观点:

Distance to start cell = 0

Previous cell for start = some not existed cell

Add start cell to queue

Mark start cell as visited

While queue is not empty

     Take off cell Y from queue, if cell Y equal to finish cell, exit

     Check all possible moves from it (goes Up, Down, Left, Right, except "walls")

     For every possible cell adjancent from Y
            Check that possible cell X is not visited before
                 If Yes, mark X as visited and add to queue
                 Distance to cell X = distance to cell Y + 1
                 Previous cell in shortest path to cell X = Y

之后,您可以轻松地获得最短路径,从前一个阵列中的完成单元格移动。

有关更多信息,请查看维基百科 - https://en.wikipedia.org/wiki/Breadth-first_search

答案 1 :(得分:1)

简单的广度优先搜索足以解决此问题。这是Python中的一个示例实现。

<强> INPUT.TXT

4 4
1 1 4 4
1 1 0 0
0 1 0 0
0 1 1 0
0 0 1 1 

<强>解决方案:

import sys
from collections import deque
sys.stdin = open ("Input.txt", "r")
Table   = []
Queue   = deque()
Visited = set()

n, m = [int (i) for i in sys.stdin.readline().split()]
startx, starty, endx, endy = [int(i)-1 for i in sys.stdin.readline().split()]
for j in xrange(n): Table.append ([int (i) for i in sys.stdin.readline().split()])

if Table[startx][starty] == 0:
    print 0
    sys.exit(0)

def process (X, Y, Dist):
    if (X == endx and Y == endy):
        print Dist + 1
        sys.exit(0)
    if X + 1 != m and Table[X + 1][Y] and (X + 1, Y) not in Visited:
        Queue.append ((X + 1, Y, Dist + 1))
    if Y + 1 != n and Table[X][Y + 1] and (X, Y + 1) not in Visited:
        Queue.append ((X, Y + 1, Dist + 1))
    if X - 1 != -1 and Table[X - 1][Y] and (X - 1, Y) not in Visited:
        Queue.append ((X - 1, Y, Dist + 1))
    if Y - 1 != -1 and Table[X][Y - 1] and (X, Y - 1) not in Visited:
        Queue.append ((X, Y - 1, Dist + 1))

Queue.append ((startx, starty, 0))
while (len(Queue)):
    CurrentX, CurrentY, Distance = Queue.popleft()
    if ((CurrentX, CurrentY) in Visited): continue
    Visited.add ((CurrentX, CurrentY))
    process (CurrentX, CurrentY, Distance)

答案 2 :(得分:1)

我使用简单的泛洪填充类型算法: -

create array of integers equal in size to boolean array => map
set all values in map to 0
set value at (start x, end x) to 1
found path = false
step = 1

while !found path
  for each cell in map where value == step
    for each valid adjacent cell
      if cell == end position
        map [cell] = step
        found path = true
        end search
      end if
      if map [adjacent cell] == 0
        map [adjacent cell] = step + 1
      end if
    end for
  end for
end while

number of steps between start cell and end cell inclusive == step

使用堆栈和队列可以非常轻松地提高效率。您需要检查没有可能路线的地图。