Skip to content

Commit 4d0ddc4

Browse files
committed
added distances_to_start_pos.py
1 parent e9a4710 commit 4d0ddc4

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
# 0 = empty field
2+
# -1 = wall
3+
# -2 = starting position
4+
5+
# replace every 0 with the minimal distance to the starting position without going through a wall
6+
# You are allowed to go right, left, up and down. Diagonal moves are not allowed
7+
# if there is no possibility to reach a 0, just leave it as a 0
8+
9+
# input:
10+
# n by n (n == n)
11+
12+
# example:
13+
# [-2, 0, 0, -1] -> [-2, 1, 2, -1]
14+
# [0, -1, 0, -1] -> [1, -1, 3, -1]
15+
16+
arr = [
17+
[0, -2, -1, 0],
18+
[0, -1, 0, -1],
19+
[0, 0, 0, -1],
20+
[-1, -1, 0, 0]
21+
]
22+
sol = [
23+
[1, -2, -1, 0],
24+
[2, -1, 6, -1],
25+
[3, 4, 5, -1],
26+
[-1, -1, 6, 7]
27+
]
28+
29+
30+
def solve(arr: list[list[int]]) -> list[list[int]]:
31+
"""changes all zero's to the distance to the starting position (-2)
32+
if they are reachable, the not reachable zero's stays as zero's.
33+
The modified arr will also be returned."""
34+
visited, start_pos = create_seq(arr)
35+
36+
depth_search(arr, *start_pos, visited, 0)
37+
return arr
38+
39+
def depth_search(arr: list[list[int]], x: int, y: int, visited: list[list[bool]], depth: int=0) -> None:
40+
"""goes through all reachable zero's in the arr list and changes
41+
it's value to the distance to the starting position"""
42+
if arr[x][y] == 0:
43+
arr[x][y] = depth
44+
45+
visited[x][y] = True
46+
depth += 1
47+
48+
if x+1 < len(arr) and not visited[x+1][y] and arr[x+1][y] == 0:
49+
depth_search(arr, x+1, y, visited, depth)
50+
if y+1 < len(arr[x]) and not visited[x][y+1] and arr[x][y+1] == 0:
51+
depth_search(arr, x, y+1, visited, depth)
52+
if y-1 >= 0 and not visited[x][y-1] and arr[x][y-1] == 0:
53+
depth_search(arr, x, y-1, visited, depth)
54+
if x-1 >= 0 and not visited[x-1][y] and arr[x-1][y] == 0:
55+
depth_search(arr, x-1, y, visited, depth)
56+
57+
def create_seq(arr: list) -> tuple[list[list[bool]], tuple[int]]:
58+
"""Returns a visited list with lists of booleans
59+
and the starting position as a tuple"""
60+
result = []
61+
for x in range(len(arr)):
62+
result.append([])
63+
for y in range(len(arr[0])):
64+
if arr[x][y] == -2:
65+
result[x].append(True)
66+
start = (x, y)
67+
elif arr[x][y] == -1:
68+
result[x].append(True)
69+
else:
70+
result[x].append(False)
71+
72+
return result, start
73+
74+
75+
76+
77+
if __name__ == "__main__":
78+
solve(arr)
79+
print(arr)
80+
print(sol == arr)

0 commit comments

Comments
 (0)