Knight's Move

Time limit1sMemory limit256 MB

Summary
Given an l by l board and two squares, find the minimum number of knight moves between them.
Level

Medium4 of 10

Topics
BFS, Graph, Shortest path
Solved
No attempts yet

Problem

A knight is placed on a chessboard. In a single move the knight jumps in an L-shape: two squares in one direction and then one square perpendicular to it. From any square it can therefore reach up to 8 different squares.

Given the target square the knight wants to reach, determine the minimum number of moves needed to get there.

Input

The first line contains the number of test cases.

Each test case consists of three lines.

  • Line 1: the side length ll of the chessboard (4≤l≤3004 \le l \le 300). The board is l×ll \times l, and each square is written as a coordinate pair in {0,…,l−1}×{0,…,l−1}\{0, \dots, l-1\} \times \{0, \dots, l-1\}.
  • Line 2: the coordinates of the square the knight currently stands on.
  • Line 3: the coordinates of the target square the knight wants to reach.

Output

For each test case, print on its own line the minimum number of moves the knight needs to travel from the starting square to the target square.

Examples1

  1. Example 1

    Input
    3
    8
    0 0
    7 0
    100
    0 0
    30 50
    10
    1 1
    1 1
    
    Expected output
    5
    28
    0