Please subscribe to the official Codeforces channel in Telegram via the link: https://t.me/codeforces_official. ×

TooWeak_TooSlow's blog

By TooWeak_TooSlow, history, 3 months ago, In English,

Hello Everyone, I am trying to solve this problem. but not able to come up with a solution. can someone help me with solving the problem any approach/hint.

Problem Statement: Given a square chessboard of N x N size, the position of Knight and position of a target is given. We need to find out minimum steps a Knight will take to reach the target position. Only Perpendicular Moves Are Allowed.

Constraints:

1<=N<=150. 0<=StartX<=64 0<=StartY<=64

0<=EndX<=64 0<=EndY<=64

StartX and StartY Indicate Starting Location. EndX and Endy Indicate Ending Location.

Test Case:

Input:

N=8 startX and StartY = 0,5

endX and endY = 6,5

output: 3

 
 
 
 

»
3 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by TooWeak_TooSlow (previous revision, new revision, compare).

»
3 months ago, # |
  Vote: I like it +5 Vote: I do not like it

How is the output 3?

»
3 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Looks like straightforward bfs

»
3 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Represent the grid as a graph and do a breadth first search from the starting point.

  • »
    »
    3 months ago, # ^ |
      Vote: I like it -6 Vote: I do not like it

    But moves are prependucilar so simple bfs algorithm will work? Can you explain briefly if possible.

    • »
      »
      »
      3 months ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      I think n00bie has already explained the approach. Regarding what to do to avoid out of bounds. Assume I am at point (i,j) and want to add edges. I want to add edges from (i,j) to (i+1, j+2), (i+2,j+1), (i-1,j-2) and (i-2,j-1). Before I add each of these edges I check to see the destination point is in the grid. If is it not I don't add the edge.