地图上两点之间的总移动次数

问题描述 投票:0回答:1

求 5x5 二维地图中两点(p 代表距离)之间的距离(x 代表距离)。输入是一个字符串,每个逗号代表下一行或下一层。你只能向上、向下、向左、向右移动。示例:xxxxx、xxxxx、xxxxx、xxxpx、xxxxx。 这里的答案是2。

#shortest distance between two point, with x representing distance
import numpy as np
map= input()
lst = []
#filtering out commas
for points in map:
    if points.isalpha()==True:
        lst.append(points)
#converting list of points to array
axis= np.array(lst)
#turning 1d array to 5d
twoD_axis= axis.reshape(5,5)
#to collect index of array with "p"
row=[]
#to collect index of "p" in array
column=[]
count=-1
#iterating through array,checking for "p"and using "count" to get index of array with "p"
for i in twoD_axis:
    count+=1
    if "p" in i:
        #keeping index of p in "row"
        row.append(count)
count_2=-1
#iterating through array with "p",using "count" to get index of first "p"
for i in twoD_axis[row[0]]:
    count_2+=1
    if i=="p":
        #keeping index of first p in "column"
        column.append(count_2)
count_3=-1
#iterating through array with "p",using "count" to get index of second "p"
for i in twoD_axis[row[1]]:
    count_3+=1
    if i=="p":
        #keeping index of second p in "column"
        column.append(count_3)
#subtracting indexes of ps, to get number of xs going down
vertical= row[1]-row[0]
#subtracting indexes of ps, to get number of xs going left or right    
horizontal= column[1]-column[0]
#summming all xs 
print(vertical+horizontal)

        

我发现,在数学上,我们可以通过减去 p 的索引来获得 xs 的数量,但对于垂直和水平移动。它用 ps 获取数组的索引,减去它可以得到它们之间垂直的 xs,减去数组中 p 的索引,可以得到水平的 xs。这个测试运行在相同的行上尝试了 p ,这是我没想到的。我不知道还能尝试什么,但它适用于不同行上的 p。

python numpy
1个回答
0
投票

您实现的解决方案似乎非常接近,但让我们对其进行一些清理并解决一些问题。澄清一下,这是使用曼哈顿距离公式的基本寻路问题(因为我们只能向上、向下、向左和向右移动)。

以下是改进:

输入处理:您可以直接将输入拆分为行,无需手动过滤逗号。 查找“p”的位置:我们可以使用更简单的方法,而不是多次迭代来定位“p”。 曼哈顿距离公式:仅允许正交移动的网格中两点 (x1, y1) 和 (x2, y2) 之间的最短距离为 |x2 - x1| + |y2 - y1|。 让我们清理您的解决方案:

import numpy as np

# Input processing
map_input = input().split(',')

# Convert the input into a 2D numpy array
twoD_axis = np.array([list(row) for row in map_input])

# Find the positions of 'p'
positions = np.argwhere(twoD_axis == 'p')

# Extract coordinates of both 'p's
p1 = positions[0]
p2 = positions[1]

# Calculate the Manhattan distance
distance = abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])

print(distance)

对于输入“xxxpx,xxxxx,xxxxx,xxxpx,xxxxx”,将输出 2,如预期。该解决方案干净、高效,并且适用于点位于同一行或不同行的两种情况。

© www.soinside.com 2019 - 2024. All rights reserved.