将此矩阵转换为邻接表或甚至邻接表将采用O(4e)其中e表示阵列中的条目数。之后,通过BFS或DFS查找它们是否与OFS(4e)相连,因为边的数量以4e为界,每个上,下,左,右都有一个边。因此,转换到BFS或DFS大约需要O(8e)。
不进行转换的算法如下(这是一个稍微修改BFS):
int x
int y
char givenGraph[x][y]
boolean pathExists
// sourceX and sourceY represent the location of the 'S'
start(int sourceX, int sourceY, int destinationX, int destinationY) {
recursiveCheck(sourceX, sourceY, destinationX, destinationY))
if(!pathExists) {
print("Path does not exist!")
}
}
recursiveCheck(int currentX, int currentY) {
if(givenGraph[currentX][currentY] == 'D') { // if the destination then say so
print("Path exists!")
pathExists = true
}
else if(givenGraph[currentX][currentY] == 'X') { // if a wall then return
return
}
else if(givenGraph[currentX][currentY] == 'C') { // if already checked return
return
}
else { // not checked yet, either 'S' or '.' so mark
givenGraph[currentX][currentY] = 'C' // for checked
}
if(currentX + 1 < x) { // check left
recursiveCheck(currentX + 1, currentY)
}
if(currentX - 1 >= 0) { // check right
recursiveCheck(currentX - 1, currentY)
}
if(currentY + 1 < y) { // check up
recursiveCheck(currentX, currentY + 1)
}
if(currentY - 1 >= 0) { // check down
recursiveCheck(currentX, currentY - 1)
}
}
这种递归算法检查上,下,左,右为每个条目,并假定“S”位置是已知的。已知'S'的复杂性大约是O(4e)。通过搜索表中的所有条目,查找'S'将会带O(e)。因此,这种算法的效率是O(5e)。
转换可以进一步优化,就像上面的算法一样。这个简化的非转换版本是为了表明它可以像转换一样高效或更高效。
另一方面,这个递归算法确实会覆盖'S'。它不得不稍微修改以免覆盖'S'。
所有你需要知道的给定的位置是连接到它的邻居,对吧?所以你只要看看每个邻居,看看他们有没有其他东西。“ – beaker