TopcoderArchive
Archive
Algorithm problem

CircularCells

Problem statement, definition, constraints, and public examples.

Problem Statement

You have a table with N rows and M columns. In a single move, you can go from your current cell to a horizontally or vertically adjacent cell. Moving up from an uppermost cell moves you to the corresponding bottommost cell. Moving down from a bottommost cell moves you to the corresponding uppermost cell. Moving left from a leftmost cell moves you to the corresponding rightmost cell. Moving right from a rightmost cell moves you to the corresponding leftmost cell.

You are currently in the cell at row r1, column c1. Return the minimum number of moves required to get to the cell at row r2, column c2. All indices are 0-based.

Definition

Class:
CircularCells
Method:
minimumMovements
Parameters:
int, int, int, int, int, int
Returns:
int
Method signature:
int minimumMovements(int N, int M, int r1, int c1, int r2, int c2)
(be sure your method is public)

Constraints

  • N and M will each be between 1 and 1,000,000, inclusive.
  • r1 and r2 will each be between 0 and N-1, inclusive.
  • c1 and c2 will each be between 0 and M-1, inclusive.

Examples

  1. 3
    3
    0
    0
    2
    2
    Returns: 2
    The best path is (0,0)->(2,0)->(2,2).
  2. 4
    6
    3
    4
    2
    0
    Returns: 3
    The best path is (3,4)->(2,4)->(2,5)->(2,0).
  3. 394
    549
    254
    477
    15
    414
    Returns: 218
  4. 942
    725
    47
    657
    604
    191
    Returns: 644
  5. 7406
    25663
    2125
    2743
    298
    19364
    Returns: 10869
  6. 28190
    17539
    24492
    4899
    951
    12432
    Returns: 12182
  7. 104161
    123266
    163
    821
    17637
    31535
    Returns: 48188
Back to all problems