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

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:
            field[i][j] = 0
            j -= 1
            field[i][j] = 2
        elif field[i][j-1] == 3:
            flag = True
            print(11-n)
            return(None)
        else:
            field[i][j-1] = 0
            n -= 1
            return([field,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:
            field[i][j] = 0
            i -= 1
            field[i][j] = 2
        elif field[i-1][j] == 3:
            flag = True
            print(11-n)
            return(None)
        else:
            field[i-1][j] = 0
            n -= 1
            return([field,n,i,j])
    return(None)

def r_move(data):
    global flag
    field,n,i,j = data[0],data[1],data[2],data[3]
    global y
    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:
            field[i][j] = 0
            j += 1
            field[i][j] = 2
        elif field[i][j+1] == 3:
            flag = True
            print(11-n)
            return(None)
        else:
            field[i][j+1] = 0
            n -= 1
            return([field,n,i,j])
    return(None)

def d_move(data):
    global flag
    field,n,i,j = data[0],data[1],data[2],data[3]
    global x
    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:
            field[i][j] = 0
            i += 1
            field[i][j] = 2
        elif field[i+1][j] == 3:
            flag = True
            print(11-n)
            return(None)
        else:
            field[i+1][j] = 0
            n -= 1
            return([field,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
    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: Time Limit Exceeded

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] = cp(field[i])
    while(j):
        if field[i][j-1] == 0:
            field[i][j] = 0
            j -= 1
            field[i][j] = 2
        elif field[i][j-1] == 3:
            flag = True
            print(11-n)
            return(None)
        else:
            field[i][j-1] = 0
            n -= 1
            return([field,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 = cp(field)
    while(i):
        if field[i-1][j] == 0:
            field[i][j] = 0
            i -= 1
            field[i][j] = 2
        elif field[i-1][j] == 3:
            flag = True
            print(11-n)
            return(None)
        else:
            field[i-1][j] = 0
            n -= 1
            return([field,n,i,j])
    return(None)

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

def d_move(data):
    global flag
    field,n,i,j = data[0],data[1],data[2],data[3]
    global x
    if i == x-1 or field[i+1][j] == 1 or n == 0:
        return(None)
    field = cp(field)
    while(i < x-1):
        if field[i+1][j] == 0:
            field[i][j] = 0
            i += 1
            field[i][j] = 2
        elif field[i+1][j] == 3:
            flag = True
            print(11-n)
            return(None)
        else:
            field[i+1][j] = 0
            n -= 1
            return([field,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
    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: Time Limit Exceeded

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] = cp(field[i])
    while(j):
        if field[i][j-1] == 0:
            field[i][j] = 0
            j -= 1
            field[i][j] = 2
        elif field[i][j-1] == 3:
            flag = True
            print(11-n)
            return(None)
        else:
            field[i][j-1] = 0
            n -= 1
            return([field,n,i,j])
    return(None)

def u_move(data):
    global x
    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)
    for _ in range(x):
        field[_][j] = cp(field[_][j])
    while(i):
        if field[i-1][j] == 0:
            field[i][j] = 0
            i -= 1
            field[i][j] = 2
        elif field[i-1][j] == 3:
            flag = True
            print(11-n)
            return(None)
        else:
            field[i-1][j] = 0
            n -= 1
            return([field,n,i,j])
    return(None)

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

def d_move(data):
    global flag
    field,n,i,j = data[0],data[1],data[2],data[3]
    global x
    if i == x-1 or field[i+1][j] == 1 or n == 0:
        return(None)
    for _ in range(x):
        field[_][j] = cp(field[_][j])
    while(i < x-1):
        if field[i+1][j] == 0:
            field[i][j] = 0
            i += 1
            field[i][j] = 2
        elif field[i+1][j] == 3:
            flag = True
            print(11-n)
            return(None)
        else:
            field[i+1][j] = 0
            n -= 1
            return([field,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
    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: Time Limit Exceeded

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 = cp(field)
    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:
            field[i][j-1] = 0
            field[i][j] = 2
            n -= 1
            return([field,n,i,j])
    return(None)

def u_move(data):
    global x
    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 = cp(field)
    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:
            field[i-1][j] = 0
            field[i][j] = 2
            n -= 1
            return([field,n,i,j])
    return(None)

def r_move(data):
    global flag
    field,n,i,j = data[0],data[1],data[2],data[3]
    global y
    if j == y-1 or field[i][j+1] == 1 or n == 0:
        return(None)
    field = cp(field)
    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:
            field[i][j+1] = 0
            field[i][j] = 2
            n -= 1
            return([field,n,i,j])
    return(None)

def d_move(data):
    global flag
    field,n,i,j = data[0],data[1],data[2],data[3]
    global x
    if i == x-1 or field[i+1][j] == 1 or n == 0:
        return(None)
    field = cp(field)
    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:
            field[i+1][j] = 0
            field[i][j] = 2
            n -= 1
            return([field,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
    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:
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()

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

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

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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:
        # Blocked immediately
        return -1
    while 0 <= sx < w and 0 <= sy < h:
        if b[sy][sx] != 0:
            break
        sx += dx
        sy += dy
    else:
        # Got out of the board
        return -1
    if b[sy][sx] == 3:
        # Reached the goal
        return i + 1
    # Hit a block
    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)

Submission status: Accepted

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

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)