在此代码中,我已应用BFS遍历从着陆节点到目标节点的路径。现在,我必须添加一个条件,即我必须检查该节点的int值是否在高程差之内。
[示例:如果我必须从2过渡到值为5或-3但Z(高程)值为4的节点,那么我将计算它们之间的绝对差并选择值为5的节点,因为它的差异小于给定的Z值
即。 | 5-2 | = 3 <= 4 [abs()函数可以在这里工作]
我的输入有点混乱,稍后我将对其进行优化。
我应该在哪里添加此条件?
class Grid:
def __init__(self, str1):
self.maze = [s.split() for s in str1.splitlines()]
def get_start_cordinates(self):
rr = landing_site_X_coordinate # start or landing coordinates
cc = landing_site_Y_coordinate
return rr, cc
def main(self, r, c):
queue = []
visited = {(r, c): (-1, -1)}
queue.append((r, c))
while len(queue) > 0:
r, c = queue.pop(0)
if r == target_Y and c == target_X: # rows and columns are jumbled
path_actual = []
while r != -1:
path_actual.append((r, c))
r, c = visited[(r, c)]
path_actual.reverse()
aa = [(t[1], t[0]) for t in path_actual]
tempo = str(aa)[1:-1]
return tempo
for dx, dy in ((-1, 0), (0, -1), (1, 0), (0, 1), (1, 1), (1, -1), (-1, 1), (-1, -1)):
new_r = r + dy
new_c = c + dx
if (0 <= new_r < len(self.maze) and
0 <= new_c < len(self.maze[0]) and
not (new_r, new_c) in visited) and :
visited[(new_r, new_c)] = (r, c)
queue.append((new_r, new_c))
file = open('input.txt') # Opening the file in the read mode
array_of_input_values = file.read().split("\n")
print(array_of_input_values)
l_of_array = len(array_of_input_values)
row_col_string = array_of_input_values[1]
no_of_cols_W = int(row_col_string[:1]) # value of W - cols|in matrix
no_of_rows_H = int(row_col_string[-1:]) # value of H - rows|in matrix
no_of_target_sites = int(array_of_input_values[4]) # value of N
matrix_array = []
landing_site = array_of_input_values[2]
landing_site_X_coordinate = int(landing_site[:1])
landing_site_Y_coordinate = int(landing_site[-1:])
Z_elevation = int(array_of_input_values[3])
for i in range(5 + no_of_target_sites, l_of_array):
matrix_array.append(array_of_input_values[i])
print(matrix_array)
sicko_conversion = '\n'.join(matrix_array)
for i in range(5, 5 + no_of_target_sites):
target_point = array_of_input_values[i]
target_X = int(target_point[-1:])
target_Y = int(target_point[:1])
maze = Grid(sicko_conversion)
path = maze.main(*maze.get_start_cordinates())
print(path)
输入为:
BFS
6 5
0 0
10
3
0 4
4 1
5 4
3 3 22 3 6 10
12 10 2 1 5 9
-1 -10 4 5 4 8
1 2 3 4 10 6
9 8 7 6 5 4
我得到的输出是:
['UCS','6 5','0 0','10','3','0 4','4 1','5 4','3 3 22 3 6 10',' 12 10 2 1 5 9','-1 -10 4 5 4 8','1 2 3 4 10 6','9 8 7 6 5 4']
[['3 3 22 3 6 10','12 10 2 1 5 9','-1 -10 4 5 4 8','1 2 3 4 10 6','9 8 7 6 5 4']
((0,0),(1,0),(2,0),(3,0),(4,0)
((0,0),(0,1),(0,2),(0,3),(1,4)
无
“没有错误的输出,IDK为什么会出现这种情况,所以请任何人也可以处理此错误吗?
这是一个小答案;我有时间。我认为BFS基本上不适合您要执行的操作。最好使用“深度优先”方法,其中每种选择均基于成本(高差)。
这基本上意味着您将要研究的是Dijkstra的算法,即Kruskal的生成树。