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


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):    
    global answer
    if count > 10:
        return 11
    
    
    
    

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

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

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

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

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

Solution (Python):
import sys
from collections import defaultdict
def dfs(d,y,x,f):
    global ans
    if d >= 10:
        return
    f_ = defaultdict(int)
    for i in f.keys():
        f_[i] = f[i]
    for t,s in vr[(y,x)]:
        if a[t][s] == 3:
            ans = min(ans,d+1)
            break
        elif f[(t,s)]:
            if s == x+1:
                break
            f_[(t,s)] = 0
            dfs(d+1,t,s-1,f_)
            f_[(t,s)] = 1
            break

    for t,s in vl[(y,x)]:
        if a[t][s] == 3:
            ans = min(ans,d+1)
            break
        elif f[(t,s)]:
            if s == x-1:
                break
            f_[(t,s)] = 0
            dfs(d+1,t,s+1,f_)
            f_[(t,s)] = 1
            break

    for t,s in vd[(y,x)]:
        if a[t][s] == 3:
            ans = min(ans,d+1)
            break
        elif f[(t,s)]:
            if t == y+1:
                break
            f_[(t,s)] = 0
            dfs(d+1,t-1,s,f_)
            f_[(t,s)] = 1
            break

    for t,s in vu[(y,x)]:
        if a[t][s] == 3:
            ans = min(ans,d+1)
            break
        elif f[(t,s)]:
            if t == y-1:
                break
            f_[(t,s)] = 0
            dfs(d+1,t+1,s,f_)
            f_[(t,s)] = 1
            break
    return
while 1:
    w,h = map(int, sys.stdin.readline()[:-1].split())
    if w == h == 0:
        break
    a = [list(map(int, sys.stdin.readline()[:-1].split())) for i in range(h)]
    vr = defaultdict(list)
    vl = defaultdict(list)
    vd = defaultdict(list)
    vu = defaultdict(list)
    f = defaultdict(int)
    for y in range(h):
        for x in range(w):
            if a[y][x] == 1:
                f[(y,x)] = 1
            if a[y][x] in [1,3]:
                for x_ in range(x):
                    vr[(y,x_)].append((y,x))
            elif a[y][x] == 2:
                sy,sx = y,x
    for y in range(h):
        for x in range(w)[::-1]:
            if a[y][x] in (1,3):
                for x_ in range(x+1,w):
                    vl[(y,x_)].append((y,x))
    for x in range(w):
        for y in range(h):
            if a[y][x] in (1,3):
                for y_ in range(y):
                    vd[(y_,x)].append((y,x))
    for x in range(w):
        for y in range(h)[::-1]:
            if a[y][x] in (1,3):
                for y_ in range(y+1,h):
                    vu[(y_,x)].append((y,x))
    ind = [[[0]*4 for i in range(w)] for j in range(h)]
    ans = 11
    dfs(0,sy,sx,f)
    ans = ans if ans < 11 else -1
    print(ans)

Solution (Python):
ans_list = []

def main():
    while True:
        ans = solve()
        if ans == "end":
            break
        ans_list.append(ans)
    
    for ans in ans_list:
        print(ans)
    
def solve():
    W,H = map(int,input().split())
    if (H,W) == (0,0):
        return "end"
    grid = [list(map(int,input().split())) for _ in range(H)]
    for i,line in enumerate(grid):
        for j,p in enumerate(line):
            if p == 2:
                si,sj = i,j
    around = [(0,1),(1,0),(0,-1),(-1,0)]
    res = [11]
    def dfs(i=si,j=sj,d=0):
        if d == 10:
            return
        for di,dj in around:
            ni = i; nj = j; nd = d
            
            if not(0 <= ni+di < H and 0 <= nj+dj < W):
                continue
            if grid[ni+di][nj+dj] == 1:
                continue
            ni += di; nj += dj; nd += 1

            while True:
                if grid[ni][nj] == 3:
                    res[0] = min(res[0],nd)
                    break
                
                if not(0 <= ni+di < H and 0 <= nj+dj < W):
                    break
                
                if grid[ni+di][nj+dj] == 1:
                    grid[ni+di][nj+dj] = 0
                    dfs(ni,nj,nd)
                    grid[ni+di][nj+dj] = 1
                    break
                ni += di; nj += dj
    
    dfs()
    if res[0] == 11:
        res[0] = -1
    return res[0]

main()

Solution (Python):


ans = 1145141919

def dfs(board,y,x,dis,count):
    global ans
    if count <= 10 and count < ans:
        if (board[y][x] == '3'):
            ans = min(ans,count)
        else:
            if (0 <= y+dis[0] < h) and (0 <= x+dis[1] < w):
                if board[y+dis[0]][x+dis[1]] != '1':
                    dfs(board,y+dis[0],x+dis[1],dis,count)
                else:
                    board[y+dis[0]][x+dis[1]] = '0'
                    for ddd in dydx:
                        ppy = y + ddd[0]
                        ppx = x + ddd[1]
                        if (0 <= ppy < h) and (0 <= ppx < w):
                            if (board[ppy][ppx] != '1'):
                                dfs(board,ppy,ppx,(ddd[0],ddd[1]),count+1)
                    board[y+dis[0]][x+dis[1]] = '1'

while True:
    try:
        w,h = map(int , input().split())
        if ((not w) and (not h)):
            break
        board = [list(input().split()) for i in range(h)]
        for y,row in enumerate(board):
            try:
                spos = (y,row.index("2"))
                break
            except ValueError:
                pass
        dydx = [[-1,0],[1,0],[0,-1],[0,1]]

        for dd in dydx:
            py = spos[0]+dd[0]
            px = spos[1]+dd[1]
            if (0 <= py < h) and (0 <= px < w):
                if (board[py][px] != '1'):
                    dfs(board,py,px,(dd[0],dd[1]),1)

        if ans == 1145141919 :
            print('-1')
        else:
            print(ans)

        ans = 1145141919
    except:
        break