Problem:
Problem D: Curling 2.0 On Planet MM-21, after their Olympic games this year, curling is getting popular.
But the rules are somewhat different from ours.
The game is played on an ice game board on which a square mesh is marked.
They use only a single stone.
The purpose of the game is to lead the stone from the start
to the goal with the minimum number of moves. Fig. D-1 shows an example of a game board.
Some squares may be occupied with blocks.
There are two special squares namely the start and the goal,
which are not occupied with blocks.
(These two squares are distinct.)
Once the stone begins to move, it will proceed until it hits a block.
In order to bring the stone to the goal,
you may have to stop the stone by hitting it against a block,
and throw again.    Fig. D-1: Example of board (S: start, G: goal)  The movement of the stone obeys the following rules:  At the beginning, the stone stands still at the start square. The movements of the stone are restricted to x and y directions.
Diagonal moves are prohibited. When the stone stands still, you can make it moving by throwing it.
You may throw it to any direction
unless it is blocked immediately(Fig. D-2(a)). Once thrown, the stone keeps moving to the same direction until
one of the following occurs:  The stone hits a block (Fig. D-2(b), (c)).  The stone stops at the square next to the block it hit. The block disappears.  The stone gets out of the board.  The game ends in failure.  The stone reaches the goal square.  The stone stops there and the game ends in success.   You cannot throw the stone more than 10 times in a game.
If the stone does not reach the goal in 10 moves, the game ends in failure.    Fig. D-2: Stone movements  Under the rules, we would like to know whether the stone at the start
can reach the goal and, if yes, the minimum number of moves required. With the initial configuration shown in Fig. D-1, 4 moves are required
to bring the stone from the start to the goal.
The route is shown in Fig. D-3(a).
Notice when the stone reaches the goal, the board configuration has changed
as in Fig. D-3(b).    Fig. D-3: The solution for Fig. D-1 and the final board configuration   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.
The number of datasets never exceeds 100.  Each dataset is formatted as follows.  the width(=w) and the height(=h) of the board   First row of the board  ...  h-th row of the board   The width and the height of the board satisfy:
 2 <= w <= 20, 1 <= h <= 20. Each line consists of w decimal numbers delimited by a space.
The number describes the status of the corresponding square.  0 vacant square  1 block  2 start position  3 goal position      The dataset for Fig. D-1 is as follows:   6 6 1 0 0 2 1 0 1 1 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 1 0 0 0 0 1 0 1 1 1 1 1   Output   For each dataset, print a line having a decimal integer indicating the
minimum number of moves along a route from the start to the goal.
If there are no such routes, print -1 instead.
Each line should not have any character other than 
this number.   Sample Input  2 1
3 2
6 6
1 0 0 2 1 0
1 1 0 0 0 0
0 0 0 0 0 3
0 0 0 0 0 0
1 0 0 0 0 1
0 1 1 1 1 1
6 1
1 1 2 1 1 3
6 1
1 0 2 1 1 3
12 1
2 0 1 1 1 1 1 1 1 1 1 3
13 1
2 0 1 1 1 1 1 1 1 1 1 1 3
0 0  Output for the Sample Input  1
4
-1
4
10
-1

Solution (Python):
def main():
  while True:
    w, h = map(int, input().split())
    if w == 0:
      break
  
    mp = [[-1] + list(map(int, input().split())) + [-1] for _ in range(h)]
    mp.insert(0, [-1] * (w + 2))
    mp.append([-1] * (w + 2))
  
    for y in range(1, h + 1):
      for x in range(1, w + 1):
        if mp[y][x] == 2:
          start = (x, y)
        if mp[y][x] == 3:
          goal = (x, y)
  
    vec = ((0, -1), (0, 1), (-1, 0), (1, 0))
    
    def search(now, goal, num):
      if num <= 0:
        return -1
      bx, by = now
      ret = -1
      for dx, dy in vec:
        if mp[by + dy][bx + dx] in (-1, 1):
          continue
        nx, ny = bx, by
        while mp[ny + dy][nx + dx] not in (-1, 1):
          nx += dx
          ny += dy
          if (nx, ny) == goal:
            ret = max(ret, num - 1)
            break
        else:
          if mp[ny + dy][nx + dx] == 1:
            mp[ny + dy][nx + dx] = 0
            ret = max(ret, search((nx, ny), goal, num - 1))
            mp[ny + dy][nx + dx] = 1
  
      return ret
  
    
    score = search(start, goal, 10)
    if score == -1:
      print(-1)
    else:
      print(10 - score)

main()

Solution (Python):
def rec(x,y,t):
    global ans
    if t >= ans: return
    if field[y][x] == 3: ans = min(ans,t)
    for dx,dy in zip([1,0,-1,0],[0,1,0,-1]):
        nx,ny = x+dx,y+dy
        while 0 <= nx < W and 0 <= ny < H:
            if field[ny][nx] == 3:
                rec(nx,ny,t+1)
            if field[ny][nx] == 1:
                if abs(nx-x)+abs(ny-y) == 1: break
                field[ny][nx] = 0
                rec(nx-dx,ny-dy,t+1)
                field[ny][nx] = 1
                break
            nx += dx; ny += dy

while 1:
    W,H = map(int,raw_input().split())
    if W == 0: break
    field = [map(int,raw_input().split()) for _ in range(H)]
    for y in range(H):
        for x in range(W):
            if field[y][x] == 2: sx,sy = x,y
    ans = 11
    rec(sx,sy,0)
    print ans if ans <= 10 else -1

Solution (Python):
dxy = zip([1,0,-1,0],[0,1,0,-1])
def rec(x,y,t):
    global ans
    if t >= ans: return
    if field[y][x] == 3: ans = min(ans,t)
    for dx,dy in dxy:
        nx,ny = x+dx,y+dy
        while 0 <= nx < W and 0 <= ny < H:
            if   field[ny][nx] == 3: ans = t
            elif field[ny][nx] == 1:
                if abs(nx-x)+abs(ny-y) == 1: break
                field[ny][nx] = 0
                rec(nx-dx,ny-dy,t+1)
                field[ny][nx] = 1
                break
            nx += dx; ny += dy

while 1:
    W,H = map(int,raw_input().split())
    if W == 0: break
    field = [map(int,raw_input().split()) for _ in range(H)]
    for y in range(H):
        for x in range(W):
            if field[y][x] == 2: sx,sy = x,y
    ans = 11
    rec(sx,sy,1)
    print ans if ans <= 10 else -1

Solution (Python):
dxy = zip([1,0,-1,0],[0,1,0,-1])
def rec(x,y,t):
    global ans
    if t >= ans: return
    for dx,dy in dxy:
        nx,ny = x+dx,y+dy
        while 0 <= nx < W and 0 <= ny < H:
            if   field[ny][nx] == 3: ans = t
            elif field[ny][nx] == 1:
                if abs(nx-x)+abs(ny-y) == 1: break
                field[ny][nx] = 0
                rec(nx-dx,ny-dy,t+1)
                field[ny][nx] = 1
                break
            nx += dx; ny += dy

while 1:
    W,H = map(int,raw_input().split())
    if W == 0: break
    field = [map(int,raw_input().split()) for _ in range(H)]
    for y in range(H):
        for x in range(W):
            if field[y][x] == 2: sx,sy = x,y
    ans = 11
    rec(sx,sy,1)
    print ans if ans < 11 else -1

Solution (Python):
delta = ((1, 0), (0, 1), (-1, 0), (0, -1))
def ds(here, field, count, lb, ub, min_count):
	if count >= min_count:
		return min_count
	ans = min_count
	for dx, dy in delta:
		nx, ny = (here[0]+dx,here[1]+dy)
		neighbor = (nx, ny)
		while lb[0] <= nx <= ub[0] and lb[1] <= ny <= ub[1]:
			if field[ny][nx] == 1:
				if (nx, ny) != neighbor:
					field[ny][nx] = 0
					ans = ds((nx-dx,ny-dy),field, count+1, lb, ub, ans)
		    		field[ny][nx] = 1
				break
			if field[ny][nx] == 3:
				if count + 1 < ans:
					ans = count + 1
				break
			nx += dx
			ny += dy
	return ans
while 1:
	w, h = map(int,raw_input().split(" "))
	if w == h == 0: break
	board = [ map(int,raw_input().split(" ")) for _ in range(h)]
	for j in range(h):
		for i in range(w):
			if board[j][i] == 2:
				start = (i,j)
	result = ds(start, board, 0, (0,0), (w-1,h-1), 11)
	print result if result < 11 else -1

Solution (Python):
delta = ((1, 0), (0, 1), (-1, 0), (0, -1))
def ds(here, field, count, lb, ub, min_count):
	if count == min_count:
		return min_count
	ans = min_count
	for dx, dy in delta:
		nx, ny = (here[0]+dx,here[1]+dy)
		neighbor = (nx, ny)
		while lb[0] <= nx <= ub[0] and lb[1] <= ny <= ub[1]:
			if field[ny][nx] == 1:
				if (nx, ny) != neighbor:
					field[ny][nx] = 0
					ans = ds((nx-dx,ny-dy),field, count+1, lb, ub, ans)
		    		field[ny][nx] = 1
				break
			if field[ny][nx] == 3:
				if count + 1 < ans:
					ans = count + 1
				break
			nx += dx
			ny += dy
	return ans
while 1:
	w, h = map(int,raw_input().split(" "))
	if w == h == 0: break
	board = [ map(int,raw_input().split(" ")) for _ in range(h)]
	for j in range(h):
		for i in range(w):
			if board[j][i] == 2:
				start = (i,j)
	result = ds(start, board, 0, (0,0), (w-1,h-1), 11)
	print result if result < 11 else -1

Solution (Python):
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]


def dfs(x, y, cnt):
    global board, W, H, ans
    if cnt >= ans:
        return

    for i in range(4):
        mx = x + dx[i]
        my = y + dy[i]

        if 0 > mx or 0 > my or W <= mx or H <= my:
            continue
        if board[my][mx] == 1:
            continue

        while True:
            if board[my][mx] == 3:
                ans = cnt
                return

            mx += dx[i]
            my += dy[i]

            if 0 > mx or 0 > my or W <= mx or H <= my:
                break

            if board[my][mx] == 1:
                board[my][mx] = 0
                dfs(mx - dx[i], my - dy[i], cnt + 1)
                board[my][mx] = 1
                break

while True:
    W, H = map(int, raw_input().split())
    if W == 0:
        break

    ans = 11
    board = [map(int, raw_input().split()) for _ in range(H)]
    for y in range(H):
        for x in range(W):
            if board[y][x] == 2:
                sx, sy = x, y
    dfs(sx, sy, 1)
    print ans if ans < 11 else - 1

Solution (Python):
dx=[0,0,-1,1]
dy=[-1,1,0,0]
    
def curling(x,y,cnt):
    '''
    Map: map
    si,sj: start(x,y)
    cnt: count
    '''
    global Map
    global ans
    if (cnt>=ans):return
    
    for i in range(4):
        mx=x; my=y
        mx+=dx[i]; my+=dy[i]
        if(mx<0 or mx>=w or my<0 or my>=h):continue
        if(Map[my][mx]==1):continue

        while(True):
            if(Map[my][mx]==3):
                ans=cnt
                return
        
            mx+=dx[i]; my+=dy[i]
            if(mx < 0 or mx>=w or my < 0 or my >=h):break
            
            if(Map[my][mx]==1):
                Map[my][mx]=0
                curling(mx-dx[i],my-dy[i],cnt+1)
                Map[my][mx]=1
                break            
            
while(True):
    Map=[]
    w,h=map(int,raw_input().split(' '))
    if (w==0 and h==0):break
    for i in range(h):
        Map.append(map(int,raw_input().split(' ')))

    for y in range(h):
        for x in range(w):
            if (Map[y][x]==2):break
        else:continue
        break

    ans =11
    curling(x,y,1)
    print ans if ans < 11 else -1

Solution (Python):
def dfs_sub(i, b, sx, sy, dx, dy):
    if 0 <= sx + dx < w and 0 <= sy + dy < h and b[sy + dy][sx + dx] == 1:
        
        return -1
    while 0 <= sx < w and 0 <= sy < h:
        if b[sy][sx] != 0:
            break
        sx += dx
        sy += dy
    else:
        
        return -1
    if b[sy][sx] == 3:
        
        return i + 1
    
    if i == 9:
        return -1
    b2 = [row[:] for row in b]
    b2[sy][sx] = 0
    return dfs(i + 1, b2, sx - dx, sy - dy)


def dfs(i, b, sx, sy):
    min_ans = 100
    for dx, dy in [[0, 1], [1, 0], [0, -1], [-1, 0]]:
        cnt = dfs_sub(i, b, sx, sy, dx, dy)
        if cnt != -1:
            min_ans = min(min_ans, cnt)
    return min_ans if min_ans != 100 else -1


while True:
    w, h = [int(_) for _ in raw_input().split()]
    if w == h == 0:
        break
    board = [[int(_) for _ in raw_input().split()] for __ in xrange(h)]
    for y in xrange(h):
        for x in xrange(w):
            cell = board[y][x]
            if cell == 2:
                sx = x
                sy = y
                board[y][x] = 0
            elif cell == 3:
                gx = x
                gy = y

    print dfs(0, board, sx, sy)

Solution (Python):

dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
N_MOVE = 4
EMPTY = 0
ROCK = 1
START = 2
GOAL = 3

INF = 100000

def in_field(field, x, y):
    return y >=0 and y < len(field) and x >= 0 and x< len(field[0])


def move_to_rock(field, x, y, direction):
    while(True):
        x += dx[direction]
        y += dy[direction]
        if not in_field(field, x, y):
            return None
        elif field[y][x] == ROCK:
            x -= dx[direction]
            y -= dy[direction]
            break
        elif field[y][x] == GOAL:
            break
    return x, y


def dfs(depth, field, x, y):
    if depth > 10:
        return None

    cost = INF
    for r in range(N_MOVE):
        nx, ny = x + dx[r], y + dy[r]
        if not in_field(field, nx, ny):
            continue
        if field[ny][nx] == ROCK:
            continue
        next_pos = move_to_rock(field, x, y, r)
        if next_pos is None:
            continue
        nx, ny = next_pos
        if field[ny][nx] == GOAL:
            return depth
        rock_pos_x, rock_pos_y = nx+dx[r], ny+dy[r]
        assert field[rock_pos_y][rock_pos_x] == ROCK
        field[rock_pos_y][rock_pos_x] = EMPTY
        result = dfs(depth+1, field, nx, ny)
        if result is not None:
            cost = min(cost, result)
        field[rock_pos_y][rock_pos_x] = ROCK
    return cost


def find_start_pos(field):
    h = len(field)
    w = len(field[0])
    for y in range(h):
        for x in range(w):
            if field[y][x] == START:
                return x, y
    return None  


def solve():
    w, h = map(int, input().split())
    if w == 0 or h == 0:
        return None
    field = []
    for y in range(h):
        field.append(list(map(int, input().split())))
    x, y = find_start_pos(field)
    res = dfs(1, field, x, y)
    return res


if __name__ == '__main__':
    while(True):
        answer = solve()
        if answer is None:
            break
        elif answer == INF:
            print(-1)
        else:
            print(answer)

Solution (Python):
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
N_MOVE = 4
EMPTY = 0
ROCK = 1
START = 2
GOAL = 3
 
INF = 100000
 
def in_field(field, x, y):
    return y >=0 and y < len(field) and x >= 0 and x< len(field[0])
 
 
def move_to_rock(field, x, y, direction):
    while(True):
        x += dx[direction]
        y += dy[direction]
        if not in_field(field, x, y):
            return None
        elif field[y][x] == ROCK:
            x -= dx[direction]
            y -= dy[direction]
            break
        elif field[y][x] == GOAL:
            break
    return x, y
 
 
def dfs(depth, field, x, y):
    if depth > 10:
        return None
 
    cost = INF
    for r in range(N_MOVE):
        if cost <= depth:
            return cost
        nx, ny = x + dx[r], y + dy[r]
        if not in_field(field, nx, ny):
            continue
        if field[ny][nx] == ROCK:
            continue
        next_pos = move_to_rock(field, x, y, r)
        if next_pos is None:
            continue
        nx, ny = next_pos
        if field[ny][nx] == GOAL:
            return depth
        rock_pos_x, rock_pos_y = nx+dx[r], ny+dy[r]
        assert field[rock_pos_y][rock_pos_x] == ROCK
        field[rock_pos_y][rock_pos_x] = EMPTY
        result = dfs(depth+1, field, nx, ny)
        if result is not None:
            cost = min(cost, result)
        field[rock_pos_y][rock_pos_x] = ROCK
    return cost
 
 
def find_start_pos(field):
    h = len(field)
    w = len(field[0])
    for y in range(h):
        for x in range(w):
            if field[y][x] == START:
                return x, y
    return None  
 
 
def solve():
    w, h = map(int, input().split())
    if w == 0 or h == 0:
        return None
    field = []
    for y in range(h):
        field.append(list(map(int, input().split())))
    x, y = find_start_pos(field)
    res = dfs(1, field, x, y)
    return res
 
 
if __name__ == '__main__':
    while(True):
        answer = solve()
        if answer is None:
            break
        elif answer == INF:
            print(-1)
        else:
            print(answer)

Solution (Python):
from queue import Queue as q
from copy import deepcopy as cp

def l_move(data):
    global flag
    field,n,i,j = data[0],data[1],data[2],data[3]
    if j == 0 or field[i][j-1] == 1 or n == 0:
        return(None)
    while(j):
        if field[i][j-1] == 0:
            j -= 1
        elif field[i][j-1] == 3:
            flag = True
            print(11-n)
            return(None)
        else:
            nfield = field[:i] + [field[i][:j-1] + [0] + field[i][j:]] + field[i+1:]

            n -= 1
            return([nfield,n,i,j])
    return(None)

def u_move(data):
    global flag
    field,n,i,j = data[0],data[1],data[2],data[3]
    if i == 0 or field[i-1][j] == 1 or n == 0:
        return(None)
    while(i):
        if field[i-1][j] == 0:
            i -= 1
        elif field[i-1][j] == 3:
            flag = True
            print(11-n)
            return(None)
        else:
            nfield = field[:i-1] + [field[i-1][:j] + [0] + field[i-1][j+1:]] + field[i:]

            n -= 1
            return([nfield,n,i,j])
    return(None)

def r_move(data):
    global flag
    field,n,i,j = data[0],data[1],data[2],data[3]

    if j == y-1 or field[i][j+1] == 1 or n == 0:
        return(None)
    while(j < y-1):
        if field[i][j+1] == 0:
            j += 1
        elif field[i][j+1] == 3:
            flag = True
            print(11-n)
            return(None)
        else:
            nfield = field[:i] + [field[i][:j+1] + [0] + field[i][j+2:]] + field[i+1:]

            n -= 1
            return([nfield,n,i,j])
    return(None)

def d_move(data):
    global flag
    field,n,i,j = data[0],data[1],data[2],data[3]
    if i == x-1 or field[i+1][j] == 1 or n == 0:
        return(None)
    while(i < x-1):
        if field[i+1][j] == 0:
            i += 1
        elif field[i+1][j] == 3:
            flag = True
            print(11-n)
            return(None)
        else:
            nfield = field[:i+1] + [field[i+1][:j] + [0] + field[i+1][j+1:]] + field[i+2:]

            n -= 1
            return([nfield,n,i,j])
    return(None)

while(True):
    flag = False
    y,x = map(int,input().split())
    lis = q()
    if x == 0:
        break
    field = []
    for i in range(x):
        field.append(list(map(int, input().split())))
    for i in range(x):
        for j in range(y):
            if field[i][j] == 2:
                start_x, start_y = i,j
                field[i][j] = 0
    data = [field,10,start_x,start_y]
    lis.put(data)
    while(lis.qsize()):
        d = lis.get()
        tmp = l_move(d)
        if flag:
            break
        if tmp != None:
            lis.put(tmp)
        tmp = u_move(d)
        if flag:
            break
        if tmp != None:
            lis.put(tmp)
        tmp = d_move(d)
        if flag:
            break
        if tmp != None:

            lis.put(tmp)
        tmp = r_move(d)
        if flag:
            break
        if tmp != None:
            lis.put(tmp)

        
    if not flag:
        print(-1)

Solution (Python):

from math import sqrt
from collections import deque

def inpl(): return list(map(int, input().split()))
W, H = inpl()
while H:
    G = []
    for h in range(H):
        tmp = []
        for w, x in enumerate(inpl()):
            tmp.append(x==1)
            if x == 2:
                s = (h, w)
            if x == 3:
                g = (h, w)
        G.append(tmp)

    Q = deque()
    Q.append([s, 0, []])
    found = False
    while Q:
        s, turn, deleated = Q.popleft()
        for h, w in deleated:
            G[h][w] = False
        for dh, dw in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
            if found:
                break
            h, w = s
            for step in range(30):
                nh, nw = h+dh, w+dw
                if not ((0 <= nh < H) & (0 <= nw < W)):
                    break
                if (nh, nw) == g:
                    print(turn+1)
                    found = True
                    break
                elif G[nh][nw] == True:
                    if turn != 9 and step > 0:
                        Q.append([(h, w), turn+1, deleated + [(nh, nw)]])
                    break
                h, w = nh, nw

        for h, w in deleated:
            G[h][w] = True
        if found:
            break
    else:
        print(-1)
    W, H = inpl()

Solution (Python):








from queue import Queue as q




def l_move(data):
    global flag
    field,n,i,j = data[0],data[1],data[2],data[3]
    if j == 0 or field[i][j-1] == 1 or n == 0:
        return(None)
    while(j):
        if field[i][j-1] == 0:
            j -= 1
        elif field[i][j-1] == 3:
            flag = True
            print(11-n)
            return(None)
        else:
            nfield = field[:i] + [field[i][:j-1] + [0] + field[i][j:]] + field[i+1:]
            n -= 1
            return([nfield,n,i,j])
    return(None)

def u_move(data):
    global flag
    field,n,i,j = data[0],data[1],data[2],data[3]
    if i == 0 or field[i-1][j] == 1 or n == 0:
        return(None)
    while(i):
        if field[i-1][j] == 0:
            i -= 1
        elif field[i-1][j] == 3:
            flag = True
            print(11-n)
            return(None)
        else:
            nfield = field[:i-1] + [field[i-1][:j] + [0] + field[i-1][j+1:]] + field[i:]
            n -= 1
            return([nfield,n,i,j])
    return(None)

def r_move(data):
    global flag
    field,n,i,j = data[0],data[1],data[2],data[3]

    if j == y-1 or field[i][j+1] == 1 or n == 0:
        return(None)
    while(j < y-1):
        if field[i][j+1] == 0:
            j += 1
        elif field[i][j+1] == 3:
            flag = True
            print(11-n)
            return(None)
        else:
            nfield = field[:i] + [field[i][:j+1] + [0] + field[i][j+2:]] + field[i+1:]
            n -= 1
            return([nfield,n,i,j])
    return(None)

def d_move(data):
    global flag
    field,n,i,j = data[0],data[1],data[2],data[3]
    if i == x-1 or field[i+1][j] == 1 or n == 0:
        return(None)
    while(i < x-1):
        if field[i+1][j] == 0:
            i += 1
        elif field[i+1][j] == 3:
            flag = True
            print(11-n)
            return(None)
        else:
            nfield = field[:i+1] + [field[i+1][:j] + [0] + field[i+1][j+1:]] + field[i+2:]
            n -= 1
            return([nfield,n,i,j])
    return(None)

while(True):
    flag = False 
    y,x = map(int,input().split()) 
    lis = q() 
    if x == 0:
        break
    field = [] 
    for i in range(x):
        field.append(list(map(int, input().split()))) 
    for i in range(x):
        for j in range(y):
            if field[i][j] == 2:
                start_x, start_y = i,j 
                field[i][j] = 0
    data = [field,10,start_x,start_y] 
    lis.put(data) 
    while(lis.qsize()):
        
        
        
        
        
        d = lis.get()
        tmp = l_move(d)
        if flag:
            break
        if tmp != None:
            lis.put(tmp)
        tmp = u_move(d)
        if flag:
            break
        if tmp != None:
            lis.put(tmp)
        tmp = d_move(d)
        if flag:
            break
        if tmp != None:
            lis.put(tmp)
        tmp = r_move(d)
        if flag:
            break
        if tmp != None:
            lis.put(tmp)
    
    if not flag:
        print(-1)

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(0,-1),(1,0),(0,1),(-1,0)]
ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)

def main():
    rr = []

    while True:
        w,h = LI()
        if h == 0:
            break
        a = [LI() for _ in range(h)]
        s = t = None
        for i in range(h):
            for j in range(w):
                if a[i][j] == 2:
                    s = (i,j)
                    a[i][j] = 0
                elif a[i][j] == 3:
                    t = (i,j)
        q = set([(s,tuple())])
        tr = -1
        for i in range(1,11):
            nq = set()
            for c,l in q:
                l = list(l)
                for di,dj in dd:
                    ni = c[0]
                    nj = c[1]
                    while 0 <= ni < h and 0 <= nj < w and (a[ni][nj] == 0 or (ni,nj) in l):
                        ni += di
                        nj += dj
                    if (ni,nj) == t:
                        tr = i
                        break
                    if ni < 0 or ni >= h or nj < 0 or nj >= w:
                        continue
                    ni -= di
                    nj -= dj
                    if ni != c[0] or nj != c[1]:
                        nq.add(((ni,nj), tuple(sorted(l + [(ni+di,nj+dj)]))))
                if tr > 0:
                    break
            if tr > 0:
                break
            q = nq
        rr.append(tr)

    return '\n'.join(map(str, rr))



print(main())

Solution (Python):
dx = [0,0,-1,1]
dy = [-1,1,0,0]

def rec(n, x, y):
    global w,h,ans
    global f
    if n >= ans: return
    for i in xrange(4):
        
        mx, my = x+dx[i], y+dy[i]
        if not(0 <= mx < w and 0 <= my < h): continue
        if f[my][mx] == 1: continue

        while 1:
            if f[my][mx] == 3:
                
                ans = n
                return

            mx += dx[i]
            my += dy[i]
            if not(0 <= mx < w and 0 <= my < h):
                break
            if f[my][mx] == 1:
                f[my][mx] = 0
                
                rec(n+1, mx-dx[i], my-dy[i])
                f[my][mx] = 1
                break

while 1:
    w,h = map(int, raw_input().split())
    if not(w or h): break
    f = []
    for i in xrange(h):
        f.append(map(int, raw_input().split()))
    for i in xrange(h):
        for j in xrange(w):
            if f[i][j] == 2:
                sx,sy = j,i
                

    ans = 11
    rec(1, sx, sy)
    if (ans>10): ans = -1
    print ans

Solution (Python):


answer = 0
def up(board, pos, count):
    global answer
    
    
    
    
    
    

    y = pos[0]
    while y > 0:
        y -= 1
        if board[y][pos[1]] == 3:
            if count < answer:
                answer = count
            return count
        if board[y][pos[1]] == 1:
            board[y][pos[1]] = 0
            new_pos = [y+1, pos[1]]
            dfs(board, new_pos, count+1)
            board[y][pos[1]] = 1
            return



def down(board, pos, count):
    global answer
    
    
    
    
    
    

    y = pos[0]
    while y < len(board) - 1:
        y += 1
        if board[y][pos[1]] == 3:
            if count < answer:
                answer = count
            return
        if board[y][pos[1]] == 1:
            board[y][pos[1]] = 0
            new_pos = [y-1, pos[1]]
            dfs(board, new_pos, count+1)
            board[y][pos[1]] = 1
            return

        

def left(board, pos, count):
    global answer
    
    
    
    
    
    

    x = pos[1]
    while x > 0:
        x -= 1
        if board[pos[0]][x] == 3:
            if count < answer:
                answer = count
            return
        if board[pos[0]][x] == 1:
            board[pos[0]][x] = 0
            new_pos = [pos[0], x+1]
            dfs(board, new_pos, count+1)
            board[pos[0]][x] = 1
            return

def right(board, pos, count):
    global answer 
    
    
    
    
    
    

    x = pos[1]
    while x < len(board[0]) - 1:
        x += 1
        if board[pos[0]][x] == 3:
            if count < answer:
                answer = count
            return
        if board[pos[0]][x] == 1:
            board[pos[0]][x] = 0
            new_pos = [pos[0], x-1]
            dfs(board, new_pos, count+1)
            board[pos[0]][x] = 1
            return
    

def dfs(board, pos, count):    
    if count > 10:
        return 11
    
    
    
    

    
    
    
            
    h = len(board)
    w = len(board[0])

    if pos[0] - 1 >= 0 and board[pos[0]-1][pos[1]] != 1:
        up(board, pos, count)
    if pos[1] - 1 >= 0 and board[pos[0]][pos[1]-1] != 1:
        left(board, pos, count)
    if pos[0] + 1 < h and board[pos[0]+1][pos[1]] != 1:
        down(board, pos, count)
    if pos[1] + 1 < w and board[pos[0]][pos[1]+1] != 1:
        right(board, pos, count)

    return
                 
def func():
    '''

    '''
    global answer

    while True:
        w, h = map(int, raw_input().split())
        if w == 0 and h == 0:
            break
        board = []
        for i in range(h):
            row = map(int, raw_input().split())
            board.append(row)

        s = [0, 0]
        for i in range(h):
            for j in range(w):
                if board[i][j] == 2:
                    s[0] = i
                    s[1] = j
        answer = 11
        dfs(board, s, 1)
        if answer == 11:
            answer = -1
        print answer
    return None

if __name__ == '__main__':
    func()