2

Recently in an interview, I was asked this question:

You are given two cells on a chess board, one is starting cell and another one is destination cell. You will get a list of cells also, which represents blocked cells, that means you can't drop on this cells during a tour. Now you have to find a minimum number of steps to reach destination cell from the starting cell with a Knight. Given that the chess grid is infinite.

So my thought was using Breadth First Search, but the problem is if the destination is not reachable, the code will be in an infinite loop.

How to solve it?

false
  • 10,264
  • 13
  • 101
  • 209
Ahmad Faiyaz
  • 316
  • 4
  • 16

2 Answers2

5

Given that there are only finitely many blocking cells, if the two cells are not reachable from each other, one of the cells must have only finitely many reachable cells.

(otherwise, if there are two infinite region, the "barrier" between the region must take infinitely many blocking cells)

Now the solution is quite obvious. Just do a parallel BFS from both the source and the target. If either search terminates, then there are no path.

user202729
  • 3,358
  • 3
  • 25
  • 36
  • I thought about this, this algorithm works for reachability check, but what about minimum steps? The first place where the two BFS meet will give the minimum step? – Ahmad Faiyaz Jul 30 '18 at 07:19
0

You can limit the board to a size that is 3 rows and 3 columns bigger than the maximum coordinates of the starting cell and destination cell, meaning:

rows = Max(starting cell row no + 3, destination cell row no + 3) 
cols = Max(starting cell column no + 3, destination cell column no + 3)

Why? If you consider how the knight moves you will see that you can always reach any distination cell with the smallest number of moves within the above limits for the chessboard. The most "costly" situation is when you have the cells aligned diagonally e.g. starting cell A1 and destination cell B2, then you need to go C2, E3, C4 and finally B2 - 4 moves. All other situations are quicker and require less "space".

v0rin
  • 510
  • 4
  • 11