我正在尝试构建一个我在dijkstra中使用的图表。 我写了这段代码:
def build_graph(self,board):
G={} # dictionary that use as graph for dijkstra
len_x=len(board)
len_y=len(board[0])
for x in range(0,len(board)):
for y in range(0,len(board[x])):
if board[x][y]!=99:
if (len_y>(y-1)>=0):
if board[x][y-1]==90:
G[(x,y)]={(x,y-1):6 } # [location ,weight]
if board[x][y-1]==10 or board[x][y+1]==12:
G[(x,y)]={(x,y-1):1 } # case 10 or 12 --> clean path
if (len_y>(y+1)>=0):
if board[x][y+1]==90:
G[(x,y)][(x,y+1)]=6
if board[x][y+1]==10 or board[x][y+1]==12:
G[(x,y)][(x,y+1)]=1
if (0<=(x+1)<len_x):
if board[x+1][y]==90:
G[(x,y)][(x+1,y)]=6
if board[x+1][y]==10 or board[x+1][y]==12:
G[(x,y)][(x+1,y)]=1
if (0<=(x-1)<len_x):
if board[x-1][y]==90:
G[(x,y)][(x-1,y)]=6
if board[x-1][y]==10 or board[x-1][y]==12 :
G[(x,y)][(x-1,y)]=1
return G
此声明中的键错误(0,0):
G [(X,Y)] [(X,Y + 1)] = 1 而且我不知道为什么会得到它?
答案 0 :(得分:1)
您尝试在G[(0, 0)]
创建之前使用字典。尝试在内部循环的顶部为它分配一个空字典,如下所示:
def build_graph(self,board):
G={} # dictionary that use as graph for dijkstra
len_x=len(board)
len_y=len(board[0])
for x in range(0,len(board)):
for y in range(0,len(board[x])):
G[(x,y)] = {}
...