-
Notifications
You must be signed in to change notification settings - Fork 0
/
2-dont-get-volunteered.py
91 lines (68 loc) · 2.71 KB
/
2-dont-get-volunteered.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import heapq
from collections import defaultdict
# Defining chessboard parameters
BOARD_SIZE = 8
BOARD_MOVEMENTS = [(1, 2), (1, -2), (-1, 2), (-1, -2),
(2, 1), (2, -1), (-2, 1), (-2, -1)]
class Node:
def __init__(self, x, y, distance=0):
self.x = x
self.y = y
self.distance = distance
def __hash__(self):
return hash(tuple(self))
def __iter__(self):
for i in [self.x, self.y]:
yield i
def __eq__(self, node):
return self.x == node.x and self.y == node.y
def __lt__(self, other):
return self.x < node.x or (self.x == node.x and self.y < node.y)
def __str__(self):
return "<Node (x=%d, y=%d, d=%.02f)>" % (self.x, self.y, self.distance)
def __repr__(self):
return self.__str__()
class Board:
def __init__(self, size, movements):
self.size = size
self.movements = movements
def node(self, position):
""" Generate Node for given position """
return Node(int(position % self.size) + 1, int(position / self.size) + 1)
def valid(self, x, y):
return True if x >= 0 < self.size and y >= 0 < self.size else False
def distance(self, start, end):
""" Find shortest distance using BFS """
queue = []
queue.append(start)
visited = {}
# Run until queue is empty
while queue:
# Take first node in queue
node = queue.pop(0)
# Return when destination reached
if node == end:
return node.distance
# Process nodes that have not been visited
if node == end:
return node.distance
# Process nodes that have not been visited
if node not in visited:
# Mark node as visited
visited[node] = True
# Validate piece movement
for offset in self.movements:
x, y = list(tuple(x + y for x, y in zip(tuple(node), offset)))
# Queue valid moves only
if self.valid(x, y):
queue.append(Node(x, y, node.distance + 1))
return float('inf')
def solution(src, dest):
# Create chessboard graph
chessboard = Board(size = BOARD_SIZE, movements = BOARD_MOVEMENTS)
# Create coordinates
start = chessboard.node(src)
end = chessboard.node(dest)
# Calculate distance between given positions
distance = chessboard.distance(start, end)
return distance