## Teleportation Tangle

View as PDF

Points: 7 (partial)
Time limit: 2.0s
Memory limit: 512M

Author:
Problem type
Allowed languages
Ada, Assembly, Awk, Brain****, C, C#, C++, COBOL, CommonLisp, D, Dart, F#, Forth, Fortran, Go, Groovy, Haskell, Intercal, Java, JS, Kotlin, Lisp, Lua, Nim, ObjC, OCaml, Octave, Pascal, Perl, PHP, Pike, Prolog, Python, Racket, Ruby, Rust, Scala, Scheme, Sed, Swift, TCL, Text, Turing, VB, Zig

Kevin is trapped in a maze filled with many rooms and needs your help to escape!

The maze can be modelled as an by grid consisting of positive integers, where each integer represents a room. Let denote the index of Kevin's current row and column respectively, and let denote the positive integer at . From any room , Kevin can teleport exactly rooms up, down, left, or right. Also, if Kevin reaches a border, he loops around to the other side.

Looping around is defined as, from any room , moving to or .

Given that Kevin starts at the top left corner and the exit is at the bottom right corner, print the minimum number of times he needs to teleport to reach the exit. If it is impossible, print FOREVER to signify that Kevin will never escape the maze!

#### Input Specification

The first line will contain positive integers and , the number of rows and columns in the maze.

The next lines will contain positive integers in the range, .

#### Output Specification

Print the minimum number of times Kevin needs to teleport to reach the exit. If it is impossible to reach the exit, print FOREVER.

All integers in the input will be in the range .

#### Sample Input 1

3 3
2 4 3
1 1 2
6 5 8

#### Sample Output 1

3

#### Explanation for Sample Output 1

There are multiple solutions. In one solution, Kevin teleports left two rooms looping around to . Then, he teleports up four rooms looping around to . Finally, he teleports left five rooms to loop around and reach .

#### Sample Input 2

3 3
2 5 9
1 9 3
6 3 8

#### Sample Output 2

FOREVER

#### Explanation for Sample Output 2

There is no way to get from to , and Kevin will never escape the maze!