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: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]


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

    for i in range(4):
        mx, my = x, y
        mx += dx[i]
        my += 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]
            mx += 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:
                dfs(x, y, 1)
                break
    print ans if ans < 11 else - 1

# 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 True:
#     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

Submission status: Wrong Answer

Solution code:
global n,m

def move(state, dirc):
    A =state[0]
    st=state[1]
    while(st[0]>0 and st[0]<m+1 and st[1]>0 and st[1]<n+1):
        st=map(lambda x,y: x+y, st, dirc)
        if A[st[0]][st[1]]==3:
            return [A, [m+1,n+1]]
        elif A[st[0]][st[1]]==1:
            A[st[0]][st[1]]=0
            st=map(lambda x,y: x-y, st, dirc)
            return [A,st]
    return [A,[0,0]]


while(1):
    n,m=map(int, raw_input().split())
    if n==0: break
    A=[[0 for x in range(n+2)]]
    for i in range(m):
        A.append([0]+ map(int, raw_input().split()) +[0])
    A.append([0 for x in range(n+2)])
    st=[0,0]
    en=[0,0]
    for i in range(m+2):
        for j in range(n+2):
            if A[i][j]==2:
                st=[i,j]
                A[i][j]=0
            if A[i][j]==3:
                en=[i,j]
    state=[[A, st]]
    D=[[0,1],[0,-1],[1,0],[-1,0]]
    bkf=0
    for ii in range(1,11):
        #print ii
        #print state
        newstate=[]
        for St in state:
            for d in D:
                As=St[0]
                sts=St[1]
                if As[sts[0]+d[0]][sts[1]+d[1]]!=1:
                    nst=move(St, d)
                    if nst[1][0]==m+1:
                        print ii
                        bkf=1
                    elif nst[1][0]!=0:
                        newstate.append(nst)
        if bkf: break
        state=newstate[:]
    else:
        print -1

Submission status: Wrong Answer

Solution code:
while():
    w, h = map(int, input().split())
    if w == 0 or h == 0:
        break
    field = []
    for y in range(h):
        field.append(map(int, input().split()))
    print(-1)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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)
    field[i][j] = 0
    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)
    field[i][j] = 0
    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)
    field[i][j] = 0
    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)
    field[i][j] = 0
    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:]
            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: Wrong Answer

Solution code:
print(1)

Submission status: Wrong Answer

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.pop()
        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) and (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: Wrong Answer

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 ni >= 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: Time Limit Exceeded

Solution code:
import copy
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

    que = [[sx,sy,10,field[:]]]
    while que:
        x,y,t,field = que.pop(0)
        if t == -1: continue
        if field[y][x] == 3:
            print 10-t
            break
        for dx,dy in zip([1,0,-1,0],[0,1,0,-1]):
            _field = copy.deepcopy(field[:])
            nx,ny = x+dx,y+dy
            while 0 <= nx < W and 0 <= ny < H:
                if _field[ny][nx] == 3:
                    que.append([nx,ny,t-1,_field[:]])
                    break
                if _field[ny][nx] == 1:
                    _field[ny][nx] = 0
                    if abs(nx-x)+abs(ny-y) == 1: break
                    que.append([nx-dx,ny-dy,t-1,_field[:]])
                    break
                nx += dx; ny += dy
    else:
        print -1

Submission status: Time Limit Exceeded

Solution code:
from copy import deepcopy as dcp
delta = ((1, 0), (0, 1), (-1, 0), (0, -1))
def ds(here, lb, ub, field, count):
	result = 11
	for dx, dy in delta:
		next = (here[0]+dx,here[1]+dy)
		if ( not (lb[0] <= next[0] <= ub[0] and lb[1] <= next[1] <= ub[1]) or
		   field[next[1]][next[0]] == 1) :
		    continue
		tmp = slide(next, (dx,dy), lb, ub, dcp(field), count + 1) 
		if tmp < result :
			result = tmp
	return result

def slide(here, di, lb, ub, field, count):
	while lb[0] <= here[0] <= ub[0] and lb[1] <= here[1] <= ub[1]:
		if here == goal:
			return count
		if field[here[1]][here[0]] == 1:
			field[here[1]][here[0]] = 0
			return ds((here[0]-di[0],here[1]-di[1]), lb, ub, field, count)
		here = (here[0]+di[0],here[1]+di[1])
	else:
		return 11
while 1:
	w, h = map(int,raw_input().split(" "))
	if w == h == 0: break
	board = [[0 for _ in range(w)] for _ in range(h)]
	for j in range(h):
		inp = map(int,raw_input().split(" "))
		for i in range(w):
			tmp = inp[i]
			if tmp == 0: continue
			if tmp == 1: board[j][i] = 1
			elif tmp == 2: start = (i,j)
			else : goal = (i,j)
	count = ds(start, (0,0), (w-1,h-1), board, 0) 
	print count if count < 11 else -1

Submission status: Time Limit Exceeded

Solution code:
from copy import deepcopy as dcp
delta = ((1, 0), (0, 1), (-1, 0), (0, -1))
def ds(here, lb, ub, field, count):
	result = 11
	if count == 11:
		return count
	for dx, dy in delta:
		next = (here[0]+dx,here[1]+dy)
		if ( not (lb[0] <= next[0] <= ub[0] and lb[1] <= next[1] <= ub[1]) or
		   field[next[1]][next[0]] == 1) :
		    continue
		tmp = slide(next, (dx,dy), lb, ub, dcp(field), count + 1) 
		if tmp < result:
			result = tmp
	return result

def slide(here, di, lb, ub, field, count):
	while lb[0] <= here[0] <= ub[0] and lb[1] <= here[1] <= ub[1]:
		if here == goal:
			return count
		if field[here[1]][here[0]] == 1:
			field[here[1]][here[0]] = 0
			return ds((here[0]-di[0],here[1]-di[1]), lb, ub, field, count)
		here = (here[0]+di[0],here[1]+di[1])
	else:
		return 11
while 1:
	w, h = map(int,raw_input().split(" "))
	if w == h == 0: break
	board = [[0 for _ in range(w)] for _ in range(h)]
	for j in range(h):
		inp = map(int,raw_input().split(" "))
		for i in range(w):
			tmp = inp[i]
			if tmp == 0: continue
			if tmp == 1: board[j][i] = 1
			elif tmp == 2: start = (i,j)
			else : goal = (i,j)
	count = ds(start, (0,0), (w-1,h-1), board, 0) 
	print count if count < 11 else -1

Submission status: Time Limit Exceeded

Solution code:
delta = ((1, 0), (0, 1), (-1, 0), (0, -1))
def ds(here, lb, ub, field, count):
	result = 11
	if count == 11:
		return count
	for dx, dy in delta:
		next = (here[0]+dx,here[1]+dy)
		if ( not (lb[0] <= next[0] <= ub[0] and lb[1] <= next[1] <= ub[1]) or
		   field[next[1]][next[0]] == 1) :
		    continue
		tmp = slide(next, (dx,dy), lb, ub, field, count + 1) 
		if tmp < result:
			result = tmp
	return result

def slide(here, di, lb, ub, field, count):
	while lb[0] <= here[0] <= ub[0] and lb[1] <= here[1] <= ub[1]:
		if here == goal:
			result = count
			break
		if field[here[1]][here[0]] == 1:
			field[here[1]][here[0]] = 0
			result = ds((here[0]-di[0],here[1]-di[1]), lb, ub, field, count)
			field[here[1]][here[0]] = 1
			break
		here = (here[0]+di[0],here[1]+di[1])
	else:
		result = 11
	return result
while 1:
	w, h = map(int,raw_input().split(" "))
	if w == h == 0: break
	board = [[0 for _ in range(w)] for _ in range(h)]
	for j in range(h):
		inp = map(int,raw_input().split(" "))
		for i in range(w):
			tmp = inp[i]
			if tmp == 0: continue
			if tmp == 1: board[j][i] = 1
			elif tmp == 2: start = (i,j)
			else : goal = (i,j)
	count = ds(start, (0,0), (w-1,h-1), board, 0) 
	print count if count < 11 else -1

Submission status: Time Limit Exceeded

Solution code:
delta = ((1, 0), (0, 1), (-1, 0), (0, -1))
def ds(here, field, count, lb, ub):
	if count == 11:
		return count
	ans = 11
	for dx, dy in delta:
		neighbor = (here[0]+dx,here[1]+dy)
		nx, ny = neighbor
		tmp = 11
		while lb[0] <= nx <= ub[0] and lb[1] <= ny <= ub[1]:
			if field[ny][nx] == 1:
				if not(nx == neighbor[0] and ny == neighbor[1]):
					field[ny][nx] = 0
					tmp = ds((nx-dx,ny-dy),field, count+1, lb, ub)
		    		field[ny][nx] = 1
				break
			if field[ny][nx] == 3:
				tmp = count + 1
				break
			nx += dx
			ny += dy
		if tmp < ans:
			ans = tmp 
	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)
	ans = ds(start, board, 0, (0,0), (w-1,h-1)) 
	print ans if ans < 11 else -1

Submission status: Time Limit Exceeded

Solution code:
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:
		neighbor = (here[0]+dx,here[1]+dy)
		nx, ny = neighbor
		while lb[0] <= nx <= ub[0] and lb[1] <= ny <= ub[1]:
			if field[ny][nx] == 1:
				if not(nx == neighbor[0] and ny == neighbor[1]):
					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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from copy import deepcopy

def bfs(im, w, h):
    q = deque()
    for y in range(h):
        for x in range(w):
            if im[y][x] == 2:
                sy, sx = y, x
            elif im[y][x] == 3:
                gy, gx = y, x

    m = deepcopy(im)
    m[sy][sx] = 0
    q.append([sy, sx, 0, m])

    while q:
        y, x, c, m = q.popleft()
        if c >= 10:
            break
        # up
        if y-1 >= 0 and m[y-1][x] != 1:
            for ny in range(y-1, -1, -1):
                if m[ny][x] == 3:
                    return c + 1
                elif m[ny][x] == 1:
                    nm = deepcopy(m)
                    nm[ny][x] = 0
                    q.append([ny+1, x, c+1, nm])
                    break
        # down
        if y+1 < h and m[y+1][x] != 1:
            for ny in range(y+1, h):
                if m[ny][x] == 3:
                    return c + 1
                elif m[ny][x] == 1:
                    nm = deepcopy(m)
                    nm[ny][x] = 0
                    q.append([ny-1, x, c+1, nm])
                    break
        # left
        if x-1 >= 0 and m[y][x-1] != 1:
            for nx in range(x-1, -1, -1):
                if m[y][nx] == 3:
                    return c + 1
                elif m[y][nx] == 1:
                    nm = deepcopy(m)
                    nm[y][nx] = 0
                    q.append([y, nx+1, c+1, nm])
                    break
        # right
        if x+1 < w and m[y][x+1] != 1:
            for nx in range(x+1, w):
                if m[y][nx] == 3:
                    return c + 1
                elif m[y][nx] == 1:
                    nm = deepcopy(m)
                    nm[y][nx] = 0
                    q.append([y, nx-1, c+1, nm])
                    break

    return -1


while True:
    w, h = map(int, input().split())
    if w == 0:
        break
    m = [list(map(int, input().split())) for i in range(h)]
    
    print(bfs(m, w, h))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from copy import deepcopy

def bfs(im, w, h):
    q = deque()
    for y in range(h):
        for x in range(w):
            if im[y][x] == 2:
                sy, sx = y, x
            elif im[y][x] == 3:
                gy, gx = y, x

    m = deepcopy(im)
    m[sy][sx] = 0
    q.append([sy, sx, 0, m])

    while q:
        y, x, c, m = q.popleft()
        if c >= 10:
            break
        # up
        if y-1 >= 0 and m[y-1][x] != 1:
            for ny in range(y-1, -1, -1):
                if m[ny][x] == 3:
                    return c + 1
                elif m[ny][x] == 1:
                    nm = deepcopy(m)
                    nm[ny][x] = 0
                    q.append([ny+1, x, c+1, nm])
                    break
        # down
        if y+1 < h and m[y+1][x] != 1:
            for ny in range(y+1, h):
                if m[ny][x] == 3:
                    return c + 1
                elif m[ny][x] == 1:
                    nm = deepcopy(m)
                    nm[ny][x] = 0
                    q.append([ny-1, x, c+1, nm])
                    break
        # left
        if x-1 >= 0 and m[y][x-1] != 1:
            for nx in range(x-1, -1, -1):
                if m[y][nx] == 3:
                    return c + 1
                elif m[y][nx] == 1:
                    nm = deepcopy(m)
                    nm[y][nx] = 0
                    q.append([y, nx+1, c+1, nm])
                    break
        # right
        if x+1 < w and m[y][x+1] != 1:
            for nx in range(x+1, w):
                if m[y][nx] == 3:
                    return c + 1
                elif m[y][nx] == 1:
                    nm = deepcopy(m)
                    nm[y][nx] = 0
                    q.append([y, nx-1, c+1, nm])
                    break

    return -1

ws = []
hs = []
ms = []
while True:
    w, h = map(int, input().split())
    if w == 0:
        break
    m = [list(map(int, input().split())) for i in range(h)]
    
    ws.append(w)
    hs.append(h)
    ms.append(m)

for w, h, m in zip(ws, hs, ms):
    print(bfs(m, w, h))

Submission status: Time Limit Exceeded

Solution code:
import collections
import copy
drc = [(0, -1), (1, 0), (0, 1), (-1, 0)]


def in_board(r, c):
    return 0 <= r < H and 0 <= c < W


while True:
    W, H = map(int, input().split())
    if not (W | H):
        break
    origin_board = [[int(x) for x in input().split()] for _ in range(H)]
    sr, sc, gr, gc = 0, 0, 0, 0
    for r in range(H):
        for c in range(W):
            if origin_board[r][c] == 2:
                sr, sc = r, c
                origin_board[sr][sc] = 0
            elif origin_board[r][c] == 3:
                gr, gc = r, c
    que = collections.deque([(sr, sc, origin_board, 0)])
    while que:
        r, c, board, cnt = que.popleft()
        if (r, c) == (gr, gc):
            print(cnt)
            break
        for dr, dc in drc:
            nr, nc = r + dr, c + dc
            if in_board(nr, nc) and board[nr][nc] != 1:
                next_board = copy.deepcopy(board)
                while in_board(nr, nc) and board[nr][nc] == 0:
                    nr += dr
                    nc += dc
                if in_board(nr, nc) and cnt < 10:
                    if next_board[nr][nc] == 1:
                        next_board[nr][nc] = 0
                        nr, nc = nr - dr, nc - dc
                    que.append((nr, nc, next_board, cnt + 1))
    else:
        print(-1)