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

Submission status: Accepted

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

Submission status: Accepted

Solution code:


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

Submission status: Runtime Error

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:
                sx, xy = x, y
    dfs(sx, sy, 1)
    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: Runtime Error

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 == INF:
            print(-1)
        else:
            print(answer)

Submission status: Runtime Error

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[i][_] = cp(field[i][_])
    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[i][_] = cp(field[i][_])
    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)