给一张 city 的地图和一个列表 locations,问从 locations 里的每个位置到 D 的最短步数,
地图中 X 为 blocked 的部分。locations 的长度远大于 D 的数量。
类似 leetcode 286
inputs:
char[][] city = {
// 0 1 2 3 4 5 6 7 8
{'X', ' ', ' ', 'D', ' ', ' ', 'X', ' ', 'X'}, //0
{'X', ' ', 'X', 'X', ' ', ' ', ' ', ' ', 'X'}, //1
{' ', ' ', ' ', 'D', 'X', 'X', ' ', 'X', ' '}, //2
{' ', ' ', ' ', 'D', ' ', 'X', ' ', ' ', ' '}, //3
{' ', ' ', ' ', ' ', ' ', 'X', ' ', ' ', 'X'}, //4
{' ', ' ', ' ', ' ', 'X', ' ', ' ', 'X', 'X'} //5
}
int[][] locations =
{
{200, 200},
{1, 4},
{0, 3},
{5, 6},
{5, 8}
}
outputs:
int[]
[-1, 2, 0, 8, -1]- def find_dis(mapping, locations, d):
- c, r = len(mapping[0]), len(mapping)
- results = [-2] * len(locations)
- target = dict()
- for i, (ir, ic) in enumerate(locations):
- if (not 0 <= ir < r) or (not 0<= ic < c):
- results[i] = -1
- elif mapping[ir][ic] == 'X':
- results[i] = -1
- elif mapping[ir][ic] == 'D':
- results[i] = 0
- else:
- target[(ir, ic)] = i
- q = list()
- dist = dict()
- for i in range(len(d)):
- q.append((d[i][0], d[i][1]))
- dist[(d[i][0], d[i][1])] = 0
- finished = False
- while q and (not finished):
- print(q)
- print(dist)
- print(results)
- size = len(q)
- for _ in range(size):
- cur = q.pop(0)
- if cur in target:
- results[target[cur]] = dist[cur]
- if all([i != -2 for i in results]):
- finished = True
- for n in get_neib(cur, r, c):
- if (n not in dist) and (mapping[n[0]][n[1]] not in ('X', 'D')):
- q.append(n)
- dist[n] = dist[cur] + 1
- return results
-
- def get_neib(cur, R, C):
- r, c = cur
- dirs = [[0, -1], [0, 1], [-1, 0], [1, 0]]
- for dr, dc in dirs:
- nr, nc = r + dr, c + dc
- if (0 <= nr < R) and (0 <= nc < C):
- yield (nr, nc)
-
- mapping = [['X', 'D', '', ''],
- ['', 'X', '', 'D'],
- ['', '', '', 'X'],
- ['', 'X', 'D', 'X']]
- locations = [[1, 0], [0, 3], [10, 9], [0, 1]]
- d = [[0, 1], [1, 3], [3, 2]]
- print(find_dis(mapping, locations, d))
-
-
-
-
-
-
-
-
-
-
-
复制代码 |