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



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


Sample output:
1
4
-1
4
10
-1

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
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()

Submission status: Accepted

Solution code:
#提出が大幅に遅れてしまい、本当に申し訳ありません。
#着席位置は左*奥
#問題は「Curling 2.0」(http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1144&lang=jp)

#要は全探索しろという話なのですが、DFSで5日ほど頑張って結局バグが取れなかったのと、
#枝刈りができなかったのとが原因でQueueを使ったBFSに切り替えました
#無限にバグを出したので実装が相当気持ち悪い事になっています

from queue import Queue as q

#以下、しばらく上下左右それぞれの移動の関数です
#移動はとにかく一方向に見ていって、ゴールなら終わり、壁なら次の状態を返す、端までいったらNoneを返すものです
#ただし、試行回数が10を超えてしまったら強制的にNoneを返します
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 #これがTrueになったら出力して次のデータセット
    y,x = map(int,input().split()) #入力部
    lis = q() #BFS用のQueue
    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] #これから扱うデータは[盤面、残り試行回数、石のx座標、y座標]とします
    lis.put(data) #とりあえずQueueに初期状態をぶっこむ
    while(lis.qsize()):
        #後はひたすらQueueから状態を持ってきて上下左右に動かしてQueueに入れ直すことを繰り返します
        #ゴールについた瞬間に出力して次のデータセットに移ります
        #一番苦労したのはPythonだとシャローコピーのせいで盤面を直接いじれない点でした
        #かといって二次元配列のディープコピーはめちゃくちゃ遅くTLEが取れませんでした
        #仕方ないので上の実装にあるように無理やり盤面を作る方針にしました
        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)
    #最後までたどり着かなかったら-1を出力して終わり
    if not flag:
        print(-1)

Submission status: Accepted

Solution code:
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())

Submission status: Accepted

Solution code:
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):
        #print x,y
        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:
                #print f
                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
                #print mx,my
                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
                #print f

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

answer = 0
def up(board, pos, count):
    global answer
    # print 'UP:'
    # print 'pos: ' + str(pos)
    # print 'count: ' + str(count)
    # for row in board:
    #     print row
    # print 

    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
    # print 'DOWN:'
    # print 'pos: ' + str(pos)
    # print 'count: ' + str(count)
    # for row in board:
    #     print row
    # print 

    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
    # print 'LEFT:'
    # print 'pos: ' + str(pos)
    # print 'count: ' + str(count)
    # for row in board:
    #     print row
    # print 

    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 
    # print 'RIGHT:'
    # print 'pos: ' + str(pos)
    # print 'count: ' + str(count)
    # for row in board:
    #     print row
    # print 

    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
    
    # print 'DFS:'
    # print 'pos: ' + str(pos)
    # print 'count: ' + str(count)

    # for row in board:
    #     print row
    # print 
            
    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()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

answer = 0
def up(board, pos, count):
    global answer
    # print 'UP:'
    # print 'pos: ' + str(pos)
    # print 'count: ' + str(count)
    # for row in board:
    #     print row
    # print 

    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
    # print 'DOWN:'
    # print 'pos: ' + str(pos)
    # print 'count: ' + str(count)
    # for row in board:
    #     print row
    # print 

    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
    # print 'LEFT:'
    # print 'pos: ' + str(pos)
    # print 'count: ' + str(count)
    # for row in board:
    #     print row
    # print 

    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 
    # print 'RIGHT:'
    # print 'pos: ' + str(pos)
    # print 'count: ' + str(count)
    # for row in board:
    #     print row
    # print 

    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):    
    global answer
    if count > 10:
        return 11
    
    # print 'DFS:'
    # print 'pos: ' + str(pos)
    # print 'count: ' + str(count)

    # for row in board:
    #     print row
    # print 
            
    h = len(board)
    w = len(board[0])

    if count > answer:
        return

    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()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15
Dy = (-1,0,1,0)
Dx = (0,1,0,-1)

MAXH = 25
MAXW = 25
dist = [[100]*MAXW for _ in range(MAXH)]
grid = [[-1]*MAXH for _ in range(MAXH)]

def dfs(ny,nx,t,H,W):
    if t == 11:
        return
    for dy,dx in zip(Dy,Dx):
        y,x = ny,nx
        before_y,before_x = ny,nx
        while True:
            y += dy
            x += dx
            if y < 0 or y >= H:
                break
            if x < 0 or x >= W:
                break
            if grid[y][x] == 1:
                if (before_y,before_x) != (ny,nx):
                    grid[y][x] = 0
                    if dist[before_y][before_x] > t:
                        dist[before_y][before_x] = t
                    dfs(before_y,before_x,t + 1,H,W)
                    grid[y][x] = 1
                break
            if grid[y][x] == 3:
                dist[y][x] = min(t,dist[y][x])
                return
            before_y = y
            before_x = x

def solve(H,W):
    sy,sx,gy,gx = -1,-1,-1,-1
    for i in range(H):
        A = list(map(int,input().split()))
        for j in range(W):
            if A[j] == 2:
                sy,sx = i,j
            if A[j] == 3:
                gy,gx = i,j
            grid[i][j] = A[j]
            dist[i][j] = 100
    
    dist[sy][sx] = 0
    dfs(sy,sx,1,H,W)
    ans = dist[gy][gx] if dist[gy][gx] <= 10 else -1
    print(ans)

def main():
    while True:
        W,H = map(int,input().split())
        if H == 0 and W == 0:
            return
        solve(H,W)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque

def main():

    grid = []
    h,w = 0,0
    y = [1,0,-1,0]
    x = [0,1,0,-1]
    inf = 11
    gy,gx = 0,0
    ans = inf

    def inside(i,j):
        return 0<=i and i<h and 0<=j and j<w 

    def dfs(cy,cx,count):
        nonlocal ans
        if 10<count:return inf
        if ans<=count:return inf
        res = inf
        for i in range(4):
            ny = cy+y[i]
            nx = cx+x[i]
            if not inside(ny,nx):continue
            if grid[ny][nx] == 1:continue
            while True:
                if ny==gy and nx==gx:
                    ans = min(ans,count+1)
                    return count+1
                if not inside(ny+y[i],nx+x[i]):break
                if grid[ny+y[i]][nx+x[i]] == 1:break
                ny += y[i]
                nx += x[i]
            if not inside(ny+y[i],nx+x[i]):continue
            grid[ny+y[i]][nx+x[i]] = 0
            res = min(res,dfs(ny,nx,count+1))
            grid[ny+y[i]][nx+x[i]] = 1
        return res

    while True:
        w,h = map(int,input().split())
        if h == 0:break
        grid = []
        ans = inf
        for _ in range(h):
            grid.append(list(map(int,input().split())))
        sy,sx = 0,0
        for i in range(h):
            for j in range(w):
                if grid[i][j] == 2:
                    grid[i][j] = 0
                    sy,sx = i,j
                if grid[i][j] == 3:
                    grid[i][j] = 0
                    gy,gx = i,j
        res = dfs(sy,sx,0)
        if res == inf:res = -1
        print(res)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def getNewBoard(board, blockRow, blockCol):
    newBoard = []
    for row in board:
        newBoard.append(row[:])
    newBoard[blockRow][blockCol] = 0
    return newBoard

def isValidCoord(row, col, ROWS, COLS):
    return row >= 0 and row < ROWS and col >= 0 and col < COLS

def throw(direction, board, ROWS, COLS, sRow, sCol, eRow, eCol):
    if direction == 'U':
        rAdj = -1
        cAdj = 0
        if not isValidCoord(sRow + rAdj, sCol + cAdj, ROWS, COLS) \
            or board[sRow + rAdj][sCol + cAdj] == 1:
            return None, None, None

    if direction == 'D':
        rAdj = 1
        cAdj = 0
        if not isValidCoord(sRow + rAdj, sCol + cAdj, ROWS, COLS) \
            or board[sRow + rAdj][sCol + cAdj] == 1:
            return None, None, None

    if direction == 'L':
        rAdj = 0
        cAdj = -1
        if not isValidCoord(sRow + rAdj, sCol + cAdj, ROWS, COLS) \
            or board[sRow + rAdj][sCol + cAdj] == 1:
            return None, None, None

    if direction == 'R':
        rAdj = 0
        cAdj = 1
        if not isValidCoord(sRow + rAdj, sCol + cAdj, ROWS, COLS) \
            or board[sRow + rAdj][sCol + cAdj] == 1:
            return None, None, None

    while True:
        sRow += rAdj
        sCol += cAdj
        if not isValidCoord(sRow, sCol, ROWS, COLS):
            return None, None, None
        if sRow == eRow and sCol == eCol:
            return None, sRow, sCol
        if isValidCoord(sRow + rAdj, sCol + cAdj, ROWS, COLS) and board[sRow + rAdj][sCol + cAdj] == 1:
            return getNewBoard(board, sRow + rAdj, sCol + cAdj), sRow, sCol

def play(board, ROWS, COLS, sRow, sCol, eRow, eCol, numThrows):
    global minThrows

    if board == None and sRow == None and sCol == None:
        return

    if minThrows != None and numThrows >= minThrows:
        return

    if numThrows > 10:
        return

    if sRow == eRow and sCol == eCol:
        minThrows = numThrows if minThrows == None else min(minThrows, numThrows)
        return

    directions = ['U', 'D', 'L', 'R']
    for d in directions:
        if numThrows < 10:
            newBoard, newRow, newCol = throw(d, board, ROWS, COLS, sRow, sCol, eRow, eCol)
            play(newBoard, ROWS, COLS, newRow, newCol, eRow, eCol, numThrows + 1)

if __name__ == '__main__':
    while True:
        COLS, ROWS = [ int(x) for x in list(filter(lambda x: x != '', \
            input().strip().split(' '))) ]
        if ROWS == 0 and COLS == 0:
            break

        sRow = None
        sCol = None
        eRow = None
        eCol = None

        board = []
        for r in range(ROWS):
            row = [ int(x) for x in list(filter(lambda x: x != '', \
                input().strip().split(' '))) ]
            board.append(row)

            if sRow == None and sCol == None and 2 in row:
                sRow = r
                sCol = row.index(2)
                board[sRow][sCol] = 0

            if eRow == None and eCol == None and 3 in row:
                eRow = r
                eCol = row.index(3)

        minThrows = None
        play(board, ROWS, COLS, sRow, sCol, eRow, eCol, 0)

        print(minThrows if minThrows != None else -1)

Submission status: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline

def main():
    while True:
        w, h = map(int, input().split())
        if w == 0:
            break
        # 読み込み
        board = [list(map(int, input().split())) for i in range(h)]
        # 地図を整形
        # wall : ID( 1~ )
        # air: 0
        s_x, s_y, g_x, g_y = 0, 0, 0, 0; id = 1;
        for y in range(h):
            for x in range(w):
                if board[y][x] == 1:
                    board[y][x] = id
                    id += 1
                elif board[y][x] == 2:
                    s_x = x; s_y = y;
                    board[y][x] = 0
                elif board[y][x] == 3:
                    g_x = x; g_y = y;
                    board[y][x] = 0
        # スタートから幅優先探索
        search_list = deque()
        search_list.append([s_x, s_y, 0, 0, 0, [0], 1])
        ans = -1
        check = []
        while len(search_list) > 0:
            # print(search_list)
            x, y, step, dx, dy, through, count = search_list.popleft()
            if x == g_x and y == g_y:
                ans = step
                break
            if dx == 0 and dy == 0:# 動き始めの処理
                if step+1 < 11:
                    for next_x, next_y in [[x-1, y], [x+1, y], [x, y+1], [x, y-1]]:
                        if 0 <= next_x and next_x < w and 0 <= next_y and next_y < h:
                            tmp = board[next_y][next_x]
                            if tmp in through[:count]:
                                search_list.append([next_x, next_y, step+1, next_x-x, next_y-y, through[:count], count])
            else:# 壁にぶつかるまで滑る
                t_x = x; t_y = y;
                drop = False
                goal = False
                while True:
                    n_x = t_x + dx; n_y = t_y + dy;
                    if n_x == g_x and n_y == g_y:
                        ans = step
                        goal = True
                        break
                    if 0 <= n_x and n_x < w and 0 <= n_y and n_y < h:
                        if board[n_y][n_x] not in through[:count]:
                            break
                    else:
                        drop = True
                        break
                    t_x += dx; t_y += dy;
                if goal:
                    break
                if not drop:
                    tmp = board[t_y+dy][t_x+dx]
                    through = through[:count] + [tmp]
                    search_list.append([t_x, t_y, step, 0, 0, through, count+1])
        print(ans)

if __name__ == "__main__":
    main()