Skip to content

Commit cbe068c

Browse files
committed
Solution in python done
1 parent 7c01849 commit cbe068c

File tree

4 files changed

+72
-0
lines changed

4 files changed

+72
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import sys
2+
import heapq as heapriorityqueue
3+
4+
DIRECTIONS = {
5+
'N': (-1, 0), 'S': (1, 0), 'E': (0, 1), 'W': (0, -1),
6+
'NE': (-1, 1), 'NW': (-1, -1), 'SE': (1, 1), 'SW': (1, -1)
7+
}
8+
9+
def parse_input(file_path):
10+
with open(file_path, 'r') as file:
11+
lines = file.readlines()
12+
n = int(lines[0].strip())
13+
grid = [list(map(int, line.split())) for line in lines[1:]]
14+
return n, grid
15+
16+
def is_valid(x, y, n):
17+
return 0 <= x < n and 0 <= y < n
18+
19+
def find_path(n, grid):
20+
start = (0, 0)
21+
goal = (n - 1, n - 1)
22+
priorityqueue = [(0, start, [])]
23+
visited = set()
24+
25+
while priorityqueue:
26+
cost, (x, y), path = heapriorityqueue.heappop(priorityqueue)
27+
28+
if (x, y) in visited:
29+
continue
30+
visited.add((x, y))
31+
32+
if (x, y) == goal:
33+
return path
34+
35+
for direction, (dx, dy) in DIRECTIONS.items():
36+
nx, ny = x + dx, y + dy
37+
if is_valid(nx, ny, n) and grid[nx][ny] < grid[x][y]:
38+
heapriorityqueue.heappush(priorityqueue, (cost + 1, (nx, ny), path + [direction]))
39+
40+
return "IMPOSSIBLE"
41+
42+
def main():
43+
if len(sys.argv) != 2:
44+
print("Usage: python3 moves.py <input_file>")
45+
return
46+
47+
input_file = sys.argv[1]
48+
n, grid = parse_input(input_file)
49+
result = find_path(n, grid)
50+
if result == "IMPOSSIBLE":
51+
print(result)
52+
else:
53+
print('[' + ','.join(result) + ']')
54+
55+
if __name__ == "__main__":
56+
main()
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
5
2+
15 42 3 4 7
3+
17 13 67 4 32
4+
4 10 21 9 6
5+
20 7 4 20 5
6+
105 1 5 3 2
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
6
2+
88 73 71 65 54 53
3+
90 103 87 76 85 49
4+
4 29 33 38 62 47
5+
101 28 43 67 42 44
6+
27 25 32 47 100 89
7+
6 22 22 17 11 4
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
2
2+
42 17
3+
17 42

0 commit comments

Comments
 (0)