-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stacks and Queues-Castle on the Grid.py
73 lines (54 loc) · 1.63 KB
/
Stacks and Queues-Castle on the Grid.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#Problem Link : https://www.hackerrank.com/challenges/castle-on-the-grid/problem?isFullScreen=true&h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=stacks-queues
#Ans:
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'minimumMoves' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. STRING_ARRAY grid
# 2. INTEGER startX
# 3. INTEGER startY
# 4. INTEGER goalX
# 5. INTEGER goalY
#
from collections import deque
def min_moves(grid, start_x, start_y, goal_x, goal_y):
queue = deque()
queue.appendleft((start_x + 1, start_y + 1, 0))
while queue:
x, y, steps = queue.pop()
grid[x][y] = False
if x == goal_x + 1 and y == goal_y + 1:
return steps
d = 1
while grid[x][y - d]:
queue.appendleft((x, y - d, steps + 1))
d += 1
d = 1
while grid[x + d][y]:
queue.appendleft((x + d, y, steps + 1))
d += 1
d = 1
while grid[x][y + d]:
queue.appendleft((x, y + d, steps + 1))
d += 1
d = 1
while grid[x - d][y]:
queue.appendleft((x - d, y, steps + 1))
d += 1
def main():
n = int(input())
grid = [[False] * (n + 2) for _ in range(n + 2)]
for i in range(1, n + 1):
row = list(map(lambda x: x == '.', input()))
grid[i][1:-1] = row
start_x, start_y, goal_x, goal_y = map(int, input().split())
print(min_moves(grid, start_x, start_y, goal_x, goal_y))
if __name__ == '__main__':
main()