I've been practicing for an upcoming programming competition and I have stumbled across a question that I am just completely bewildered at. However, I feel as though it's a concept I should learn now rather than cross my fingers that it never comes up.
Basically, it deals with a knight piece on a chess board. You are given two inputs: starting location and ending location. The goal is to then calculate and print the shortest path that the knight can take to get to the target location.
I've never dealt with shortest-path-esque things, and I don't even know where to start. What logic do I employ to go about tackling this?
P.S. If it's of any relevance, they want you to supplement the knight's normal moves by also allowing it to move to the four corners of the square formed by the (potentially) eight moves a knight can make, given that the center of the square is the knight's location.
Yes. A Knight's Tour covers every square of the board just once. Moving from a8 through h1 and touching all the squares on the board without any restrictions on the number of repeated moves would just be a particular example of that calculation.
The knight (♘, ♞) is a piece in the game of chess, represented by a horse's head and neck. It may move two squares vertically and one square horizontally or two squares horizontally and one square vertically, jumping over other pieces.
What Is a Knight? A knight is a piece in the game of chess that is traditionally shaped like a horse. Each player begins the chess game with two knights. When setting up your chess set, place the knights on the row closest to each player, between the bishop and the rook.
The Knight is a unique piece – it can move two squares forward or backward and one square to the side, or two squares to the side and one square forward or backward, so that his movements resemble the shape of an L.
EDIT: See simon's answer, where he fixed the formula presented here.
Actually there is an O(1) formula
This is an image that I've made to visualize it ( Squares a knight can reach on Nth move are painted with same color ).
Can you notice the pattern here?
Although we can see the pattern, it is really hard to find the function f( x , y )
that returns the number of moves required to go from square ( 0 , 0 )
to square ( x , y )
But here is the formula that works when 0 <= y <= x
int f( int x , int y ) { int delta = x - y; if( y > delta ) return 2 * ( ( y - delta ) / 3 ) + delta; else return delta - 2 * ( ( delta - y ) / 4 ); }
Note: This question was asked on SACO 2007 Day 1
And solutions are here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With