Problem:
Problem D: Twirling Robot

Let's play a game using a robot on a rectangular board
covered with a square mesh (Figure D-1).
The robot is initially set at the start square in the northwest corner
facing the east direction.
The goal of this game is to lead the robot
to the goal square in the southeast corner.

Figure D-1: Example of a board

The robot can execute the following five types of commands.

"Straight":

Keep the current direction of the robot, and move forward to the next square.

"Right":

Turn right with 90 degrees from the current direction, and move forward to the next square.

"Back":

Turn to the reverse direction, and move forward to the next square.

"Left":

Turn left with 90 degrees from the current direction, and move forward to the next square.

"Halt":

Stop at the current square to finish the game.

Each square has one of these commands assigned as shown in Figure D-2.
The robot executes the command assigned to the square where it resides,
unless the player gives another command to be executed instead.
Each time the player gives an explicit command,
the player has to pay the cost that depends on the command type.

Figure D-2: Example of commands assigned to squares

The robot can visit the same square several times during a game.
The player loses the game when the robot goes out of the board
or it executes a "Halt" command before arriving at the goal square.

Your task is to write a program that calculates the minimum cost to lead the robot
from the start square to the goal one.

Input

The input is a sequence of datasets.
The end of the input is indicated by a line containing two zeros separated by a space.
Each dataset is formatted as follows.

w h

s(1,1) ... s(1,w)

s(2,1) ... s(2,w)

...

s(h,1) ... s(h,w)

c0 c1 c2 c3

The integers h and w are the numbers of rows and columns of the board,
respectively.
You may assume 2 ≤ h ≤ 30 and 2 ≤ w ≤ 30.
Each of the following h lines consists of w numbers delimited by a space.
The number s(i, j) represents the command assigned to the square
in the i-th row and the j-th column as follows.

0: "Straight"

1: "Right"

2: "Back"

3: "Left"

4: "Halt"

You can assume that a "Halt" command is assigned to the goal square.
Note that "Halt" commands may be assigned to other squares, too.

The last line of a dataset contains four integers
c0, c1, c2, and c3, delimited by a space,
indicating the costs that the player has to pay
when the player gives
"Straight", "Right", "Back", and "Left" commands
respectively.
The player cannot give "Halt" commands.
You can assume that all the values of
c0, c1, c2, and c3
are between 1 and 9, inclusive.

Output

For each dataset, print a line only having a decimal integer indicating the minimum cost
required to lead the robot to the goal.
No other characters should be on the output line.

Sample Input

8 3
0 0 0 0 0 0 0 1
2 3 0 1 4 0 0 1
3 3 0 0 0 0 0 4
9 9 1 9
4 4
3 3 4 0
1 2 4 4
1 1 1 0
0 2 4 4
8 7 2 1
2 8
2 2
4 1
0 4
1 3
1 0
2 1
0 3
1 4
1 9 3 1
0 0

Output for the Sample Input

1
11
6

Solution in Scala (judge verdict: Accepted)

import scala.annotation.tailrec
import scala.collection.mutable
import scala.io.StdIn._
object Main extends App {
  solve()
  @tailrec def solve(): Unit = {
    val Array(w, h) = readLine.trim.split(' ').map(_.toInt)
    if (w == 0 && h == 0) return
    val field = new Field(Array.tabulate(h) { _ ⇒ readLine.trim.split(' ').map(_.toInt) })
    val costs = readLine.trim.split(' ').map(_.toInt)
    val operations = Array(Straight, Right, Back, Left)
    val memo = Array.fill(h) {Array.fill(w) {Array.fill(4) {Int.MaxValue}}}
    val queue = mutable.PriorityQueue()(Ordering.by[(Int, Robot), Int](_._1).reverse)
    memo(0)(0)(1) = 0
    queue.enqueue((0, InOperation(East, Coordinate(0, 0))))
    while (queue.nonEmpty) {
      val (cost, robot) = queue.dequeue()
      if (memo(robot.position.y)(robot.position.x)(robot.direction.toInt) == cost) {
        for (op ← operations.indices) {
          val c = if (operations(op) == field(robot.position)) 0 else costs(op)
          val next = robot.execute(operations(op))
          if (next.isInOperation && field.contains(next.position) && memo(next.position.y)(next.position.x)(next.direction.toInt) > cost + c) {
            memo(next.position.y)(next.position.x)(next.direction.toInt) = cost + c
            queue.enqueue((cost + c, next))
          }
        }
      }
    }
    println(memo.last.last.min)
    solve()
  }
  class Field(state: Array[Array[Int]]) {
    private val field = state.map{_.map{
      case 0 ⇒ Straight
      case 1 ⇒ Right
      case 2 ⇒ Back
      case 3 ⇒ Left
      case 4 ⇒ Halt
      case _ ⇒ ???
    }}
    def contains(coordinate: Coordinate): Boolean = field.indices.contains(coordinate.y) && field.head.indices.contains(coordinate.x)
    def apply(coordinate: Coordinate): Operation = field(coordinate.y)(coordinate.x)
    def isGoal(coordinate: Coordinate): Boolean = field.length == coordinate.y && field.head.length - 1 == coordinate.x
  }
  sealed trait Robot {
    val direction: Direction
    val position: Coordinate
    def execute(operation: Operation): Robot
    def isInOperation: Boolean
  }
  case class InOperation(direction: Direction, position: Coordinate) extends Robot {
    override def execute(operation: Operation): Robot = {
      operation match {
        case Halt ⇒ Stopped(direction, position)
        case _ ⇒ changeDirection(operation).moveForward
      }
    }
    private def moveForward: InOperation = InOperation(direction, position.move(direction))
    private[this] def changeDirection(operation: Operation): InOperation = {
      operation match {
        case Left ⇒ InOperation(direction.turnLeft, position)
        case Right ⇒ InOperation(direction.turnRight, position)
        case Back ⇒ InOperation(direction.turnBack, position)
        case _ ⇒ this
      }
    }
    override def isInOperation: Boolean = true
  }
  case class Stopped(direction: Direction, position: Coordinate) extends Robot {
    override def execute(operation: Operation): Robot = this
    override def isInOperation: Boolean = false
  }
  sealed trait Direction {
    def turnRight: Direction = Direction.fromInt(Direction.toInt(this) + 1)
    def turnLeft: Direction = Direction.fromInt(Direction.toInt(this) + 3)
    def turnBack: Direction = Direction.fromInt(Direction.toInt(this) + 2)
    def toInt: Int = Direction.toInt(this)
  }
  object Direction{
    private def fromInt(value: Int): Direction = {
      (value % 4 + 4) % 4 match {
        case 0 ⇒ North
        case 1 ⇒ East
        case 2 ⇒ South
        case 3 ⇒ West
        case _ ⇒ ???
      }
    }
    private def toInt(direction: Direction): Int = {
      direction match {
        case North ⇒ 0
        case East ⇒ 1
        case South ⇒ 2
        case West ⇒ 3
      }
    }
  }
  object North extends Direction
  object East extends Direction
  object South extends Direction
  object West extends Direction
  case class Coordinate(x: Int, y: Int) {
    def move(direction: Direction): Coordinate = {
      direction match {
        case North ⇒ Coordinate(x, y - 1)
        case East ⇒ Coordinate(x + 1, y)
        case South ⇒ Coordinate(x, y + 1)
        case West ⇒ Coordinate(x - 1, y)
      }
    }
  }
  sealed trait Operation
  object Straight extends Operation
  object Right extends Operation
  object Back extends Operation
  object Left extends Operation
  object Halt extends Operation
}