#P9322. Super Chess Piece: Minimum Moves on an Infinite Board

    ID: 22476 Type: Default 1000ms 256MiB

Super Chess Piece: Minimum Moves on an Infinite Board

Super Chess Piece: Minimum Moves on an Infinite Board

You are given an infinite chessboard, where each cell is represented as \((r, c)\). Initially, there is exactly one piece on the board called the Super Chess Piece.

You are also given a non-empty string consisting only of characters from the set {Q, R, B, N, K, P}. Each character represents a type of chess piece, and the Super Chess Piece is allowed to move following the legal moves of any of the pieces indicated in that string. The allowed moves are defined as follows:

  • Queen (Q): Can move along the same row, column, or diagonal. Formally, from \((a, b)\), for any integer \(k\neq0\), it can move to \((a+k, b)\), \((a, b+k)\), \((a+k, b+k)\), or \((a+k, b-k)\).
  • Rook (R): Can move along the same row or column. Formally, from \((a, b)\), for any integer \(k\neq0\), it can move to \((a+k, b)\) or \((a, b+k)\).
  • Bishop (B): Can move along the diagonals. Formally, from \((a, b)\), for any integer \(k\neq0\), it can move to \((a+k, b+k)\) or \((a+k, b-k)\).
  • Knight (N): Can move in an L-shape. Formally, from \((a, b)\), it can move to one of the cells \((a+1,b+2)\), \((a+1,b-2)\), \((a+2,b+1)\), \((a+2,b-1)\), \((a-2,b+1)\), \((a-2,b-1)\), \((a-1,b+2)\), or \((a-1,b-2)\).
  • King (K): Can move one step to any of the eight adjacent cells. Formally, from \((a, b)\), it can move to \((a,b+1)\), \((a,b-1)\), \((a+1,b)\), \((a-1,b)\), \((a+1,b+1)\), \((a+1,b-1)\), \((a-1,b+1)\), or \((a-1,b-1)\).
  • Pawn (P): Can move upward by one cell. Formally, from \((a, b)\), it can move to \((a+1, b)\).

The Super Chess Piece starts at the cell \((a, b)\) and your task is to determine the minimum number of moves required to reach the target cell \((c, d)\) using any of the allowed moves in each turn. If the target cannot be reached, output -1.

Note: Other chess rules that you might be familiar with do not apply in this problem; use only the rules listed above.

inputFormat

The first line contains a non-empty string consisting of characters from {Q, R, B, N, K, P} which represents the allowed move types for the Super Chess Piece.

The second line contains four space‐separated integers \(a, b, c, d\) representing the starting cell \((a, b)\) and the target cell \((c, d)\), respectively.

outputFormat

Output a single integer: the minimum number of moves required for the Super Chess Piece to go from \((a,b)\) to \((c,d)\). If it is impossible to reach \((c,d)\), output -1.

sample

Q
1 1 8 8
1