Lintcode 611 Knight Shortest Path
https://www.lintcode.com/problem/611/description
Given a knight in a chessboard (a binary matrix with 0 as empty and 1 as barrier) with a source position, find the shortest path to a destination position, return the length of the route.
Return -1 if destination cannot be reached.
source and destination must be empty.Knight can not enter the barrier.Path length refers to the number of steps the knight takes.If the knight is at (x, y), he can get to the following positions in one step:(x + 1, y + 2)
(x + 1, y - 2)
(x - 1, y + 2)
(x - 1, y - 2)
(x + 2, y + 1)
(x + 2, y - 1)
(x - 2, y + 1)
(x - 2, y - 1)
The idea of this problem is simple, from the source
, do a BFS and find the shortest path to hit destination
.
Let’s take a look at the solution:
from typing import (
List,
)
from lintcode import (
Point,
)
"""
Definition for a point:
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
"""
class Solution:
"""
@param grid: a chessboard included 0 (false) and 1 (true)
@param source: a point
@param destination: a point
@return: the shortest path
"""
def is_valid(self, x, y, grid, distance):
return (x, y) not in distance and x >= 0 and x < len(grid) and y >= 0 and y < len(grid[0]) and grid[x][y] == 0
def shortest_path(self, grid: List[List[bool]], source: Point, destination: Point) -> int:
if source.x == destination.x and source.y == destination.y:
return 0
# write your code here
deltas = [(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)]
queue = collections.deque([(source.x, source.y)])
distance = dict({
(source.x, source.y): 0
})
while queue:
(current_x, current_y) = queue.popleft()
for delta in deltas:
(d_x, d_y) = delta
if not self.is_valid(current_x + d_x, current_y + d_y, grid, distance):
continue
if current_x + d_x == destination.x and current_y + d_y == destination.y:
return distance[(current_x, current_y)] + 1
queue.append((current_x + d_x, current_y + d_y))
distance[(current_x + d_x, current_y + d_y)] = distance[(current_x, current_y)] + 1
return -1
Pingback: Breadth First Search(BFS) - Leetcode Solution