我正在将网格网格点(2D迷宫)转换为邻接矩阵,稍后将使用它找到给定坐标之间的最短路径。请看一下我的代码:
import numpy as np
import numpy.matlib #for matrices
def cutblocks(xv,yv,allBlocks):
x_new,y_new = np.copy(xv), np.copy(yv)
ori_x,ori_y = xv[0][0], yv[0][0]
for block in allBlocks:
block = sorted(block)
block_xmin = np.min((block[0][0], block[2][0]))
block_xmax = np.max((block[0][0], block[2][0]))
block_ymin = np.min((block[0][1], block[1][1]))
block_ymax = np.max((block[0][1], block[1][1]))
rx_min, rx_max = int((block_xmin-ori_x)/stepSize)+1, int((block_xmax-ori_x)/stepSize)+1
ry_min, ry_max = int((block_ymin-ori_y)/stepSize)+1, int((block_ymax-ori_y)/stepSize)+1
for i in range(rx_min,rx_max):
for j in range(ry_min,ry_max):
x_new[j][i] = np.nan
for i in range(ry_min,ry_max):
for j in range(rx_min,rx_max):
y_new[i][j] = np.nan
return x_new, y_new
stepSize = 0.2
##Blocks that should be disabled
allBlocks = [[(139.6, 93.6), (143.6, 93.6), (143.6, 97.6), (139.6, 97.6)],
[(154.2, 93.4), (158.2, 93.4), (158.2, 97.4), (154.2, 97.4)],
[(139.2, 77.8), (143.2, 77.8), (143.2, 81.8), (139.2, 81.8)],
[(154.2, 77.8), (158.2, 77.8), (158.2, 81.8), (154.2, 81.8)],
[(139.79999999999998, 86.4),
(142.6, 86.4),
(142.6, 88.0),
(139.79999999999998, 88.0)],
[(154.79999999999998, 87.2),
(157.6, 87.2),
(157.6, 88.8),
(154.79999999999998, 88.8)]]
x = np.arange(136.0, 161.0, stepSize)
y = np.arange(75.0, 101.0, stepSize)
xv, yv = np.meshgrid(x, y)
xv, yv = cutblocks(xv,yv,allBlocks)
MazeSize = xv.shape[0]*xv.shape[1]
adj = np.matlib.zeros((MazeSize,MazeSize)) #initialize AdjacencyMatrix
#make 1 whenever there is a connection between neighboring coordinates
mazeR, mazeC = 0,0
for row in range(xv.shape[0]):
for col in range(xv.shape[1]):
if xv[row][col]>0 and col+1<xv.shape[1] and round(np.abs(xv[row][col] - xv[row][col+1]),2) == stepSize:
adj[mazeR,mazeC+1] = 1
break
mazeC = mazeC+1
mazeR = mazeR+1
此代码生成一个网格网格,其中某些点是禁用的,因为它们是迷宫中的墙。每个步骤(在连接的顶点之间)的成本为1。我的问题是: 1)邻接矩阵为N.N和N = x.y(。是乘)。正确吗?
2)在邻接矩阵中查找邻居并将其分配给值1的有效方法可能是什么。 (我尝试过,但是无法正常工作)
3)对于这类问题,我应该使用图形吗?我的最终目标是找到两个坐标(顶点)之间的最短路径。
谢谢