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 Ruby (judge verdict: Accepted)

class Heap
	require 'forwardable'
	extend Forwardable

	def initialize
		@array = []
		@index = {}
	end

	def add(obj, key)
		@array << [obj, key]
		@index[obj] = @array.size - 1
		lift_up(@array.size - 1)
	end

	def swap(i, j)
		u = @array[i]
		v = @array[j]
		@index[u[0]], @index[v[0]] = j, i
		@array[i], @array[j] = v, u
	end

	def lift_up(i)
		return if i == 0
		j = (i - 1) / 2
		if @array[i][1] < @array[j][1]
			swap(i, j)
			lift_up(j)
		end
	end

	def del_min
		raise "heap is empty!" if empty?
		min = @array[0]
		if size > 1
			swap(0, @array.size-1)
			@array.pop
			lift_down(0)
		else
			@array.pop
		end
		@index.delete(min[0])
		min
	end

	def inc_key(obj, diff)
		i = @index[obj]
		@array[i][1] += diff
		lift_down(i)
	end

	def dec_key(obj, diff)
		i = @index[obj]
		@array[i][1] -= diff
		lift_up(i)
	end

	def update_key(obj, new_key)
		i = @index[obj]
		return unless i
		return if new_key >= @array[i][1]
		@array[i][1] = new_key
		lift_up(i)
	end

	def min_obj
		@array[0][0]
	end

	def min_key
		@array[0][1]
	end

	def lift_down(i)
		j = 2 * i + 1
		k = j + 1
		if k >= size
			return if j >= size
			if @array[i][1] > @array[j][1]
				swap(i, j)
				lift_down(j)
			end
		else
			l = (@array[j][1] < @array[k][1] ? j : k)
			if @array[i][1] > @array[l][1]
				swap(i, l)
				lift_down(l)
			end
		end
	end

	def_delegators :@array, :empty?, :size
end

module Graphical
	require 'set'

	def reachable_from(s, max_depth = nil)
		reached = Set[s]
		queue = [s]
		depth = 0
		loop {
			break if max_depth && depth >= max_depth
			next_queue = []
			until queue.empty?
				u = queue.shift
				each_to_node_of(u){|v|
					next if reached.include?(v)
					reached << v
					next_queue << v
				}
			end
			break if next_queue.empty?
			queue = next_queue
			depth += 1
		}
		return reached
	end

	def dijkstra(start, setting = {})
		raise "invalid setting" if setting.class != Hash
		raise "invalid setting" if setting.keys - [:goal, :multi_source, :multi_sink, :max_dist] != []
		
		start = Set[start] if !setting[:multi_source]
		goal = setting[:goal]
		goal = Set[goal] if goal && !setting[:multi_sink]
		max_dist = setting[:max_dist]

		h = Heap.new
		reached = Set.new
		start.each{|v|
			h.add(v, 0)
			reached << v
		}

		dist = {}
		until h.empty?
			u, key = h.del_min
			return key if setting[:goal] && goal.include?(u)
			break if max_dist && key > max_dist
			dist[u] = key
			each_to_node_of(u){|v|
				d = dist[u] + edge_length(u, v)
				if reached.include?(v)
					h.update_key(v, d)
				else
					h.add(v, d)
					reached << v
				end
			}
		end
		goal ? nil : dist
	end

end


loop {
	w, h = gets.split.map &:to_i
	break if w == 0
	a = (1..h).map{ gets.split.map &:to_i }
	$command = gets.split.map &:to_i

	a.extend Graphical

	def a.each_to_node_of(u)
		y, x, dir = u
		yield [y-1, x, 0] if y > 0
		yield [y, x+1, 1] if x < self[0].size-1
		yield [y+1, x, 2] if y < self.size-1
		yield [y, x-1, 3] if x > 0
	end
	
	def a.edge_length(u, v)
		y1, x1, d1 = u
		y2, x2, d2 = v
		if self[y1][x1] == 4
			$command[(d2 - d1) % 4]
		elsif self[y1][x1] == (d2 - d1) % 4
			0
		else
			$command[(d2 - d1) % 4]
		end
	end

	p a.dijkstra([0, 0, 1], {
		:goal => (0..3).map{|dir| [h-1, w-1, dir]},
		:multi_sink => true
		})
}