Algorithm 具有不可访问单元的矩阵最短路径算法
我在一次采访中被问到这个问题。我不知道怎么做。 基本上我有一个布尔矩阵,其中0表示一个单元格不可访问。给定一个起始单元和一个目标单元,如何在不跳过任何不可访问单元的情况下构建从起始到目标的最短路径。你可以四通八达Algorithm 具有不可访问单元的矩阵最短路径算法,algorithm,Algorithm,我在一次采访中被问到这个问题。我不知道怎么做。 基本上我有一个布尔矩阵,其中0表示一个单元格不可访问。给定一个起始单元和一个目标单元,如何在不跳过任何不可访问单元的情况下构建从起始到目标的最短路径。你可以四通八达 谢谢您需要使用面包优先搜索。从这个矩形板上调制图形 主要思想是: Distance to start cell = 0 Previous cell for start = some not existed cell Add start cell to queue Mark sta
谢谢您需要使用面包优先搜索。从这个矩形板上调制图形 主要思想是:
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
之后,您可以很容易地从上一个数组的finish单元格获得最短路径
有关更多信息,请查看维基百科-一个简单的广度优先搜索就足以解决这个问题。下面是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)
我将使用一个简单的洪水填充类型算法:-
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
使用堆栈和队列可以非常轻松地提高效率。你需要检查没有可能路线的地图。Google查找路径算法。A*(“A星”)是一种流行且简单的方法。为了理解算法,提供代码通常是一个坏主意,因为人们很想复制代码,而不需要代码understanding@Mysterion我同意。但是,很多时候,当我看到算法时,我不太理解它们(可能是因为我不是以英语为母语的人)。看到示例实现总是有助于我更好地理解算法。这就是为什么我非常喜欢罗伯特·塞吉威克的书。