使用 Python 计算访问城市街区的总距离
pythonserver side programmingprogramming更新于 2025/12/25 13:32:17
假设我们有一个表示城市街区的唯一字符串矩阵,以及另一个包含要访问的街区的字符串列表。如果我们位于街区矩阵 [0][0],则找到按顺序访问每个街区所需的曼哈顿总距离。
因此,如果输入如下
| Q | B | C |
| D | E | Z |
| G | G | i |
Block = [H,B,C]
然后输出将是 6,即"h"是底部(南)2 个方块和右侧(东)1 个方块,"b"是上(北)2 个方块,"c"是右侧(东)1 个方块。
为了解决这个问题,我们将遵循以下步骤 −
- coords := 带有键"start"和值 (0, 0) 的映射
- 对于 mat 中的每一行,执行
- 对于 mat 中的每一列,执行
- 将 (row,col) 插入 coords[mat[row, col]]
- 对于 mat 中的每一列,执行
- dist := 0
- 通过添加"start"更新块开始
- 对于 i 在 0 到块大小 -1 范围内的情况,执行
- c1 := coords[blocks[i]]
- c2 := coords[blocks[i+1]]
- d := |c1[0]-c2[0]| + |c1[1]-c2[1]|
- dist := dist + d
- return dist
让我们看看下面的实现以便更好地理解 −
示例
class Solution:
def solve(self, mat, blocks):
coords = {'start': (0,0)}
for row in range(len(mat)):
for col in range(len(mat[row])):
coords[mat[row][col]] = (row,col)
dist = 0
blocks = ['start']+blocks
for i in range(len(blocks)-1):
c1 = coords[blocks[i]]
c2 = coords[blocks[i+1]]
d = abs(c1[0]-c2[0]) + abs(c1[1]-c2[1])
dist += d
return dist
ob = Solution()
inp = [["q", "b", "c"],
["d", "e", "z"],
["g", "h", "i"]]
blk = ["h", "b", "c"]
print(ob.solve(inp, blk))
输入
[["q", "b", "c"],["d", "e", "z"],["g", "h", "i"]]
输出
6
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

