Problem:


チーズ (Cheese)

問題

今年も JOI 町のチーズ工場がチーズの生産を始め，ねずみが巣から顔を出した．JOI 町は東西南北に区画整理されていて，各区画は巣，チーズ工場，障害物，空き地のいずれかである．ねずみは巣から出発して全てのチーズ工場を訪れチーズを 1 個ずつ食べる．

この町には，N 個のチーズ工場があり，どの工場も１種類のチーズだけを生産している．チーズの硬さは工場によって異なっており，硬さ 1 から N までのチーズを生産するチーズ工場がちょうど 1 つずつある．

ねずみの最初の体力は 1 であり，チーズを 1 個食べるごとに体力が 1 増える．ただし，ねずみは自分の体力よりも硬いチーズを食べることはできない．

ねずみは，東西南北に隣り合う区画に 1 分で移動することができるが，障害物の区画には入ることができない．チーズ工場をチーズを食べずに通り過ぎることもできる．すべてのチーズを食べ終えるまでにかかる最短時間を求めるプログラムを書け．ただし，ねずみがチーズを食べるのにかかる時間は無視できる． 

入力

入力は H+1 行ある．1 行目には 3 つの整数 H，W，N (1 ≤ H ≤ 1000，1 ≤ W ≤ 1000，1 ≤ N ≤ 9) がこの順に空白で区切られて書かれている．2 行目から H+1 行目までの各行には，'S'，'1', '2', ..., '9'，'X'，'.' からなる W 文字の文字列が書かれており，各々が各区画の状態を表している．北から i 番目，西から j 番目の区画を (i,j) と記述することにすると (1 ≤ i ≤ H, 1 ≤ j ≤ W)，第 i+1 行目の j 番目の文字は，区画 (i,j) が巣である場合は 'S' となり，障害物である場合は 'X' となり，空き地である場合は '.' となり，硬さ 1, 2, ..., 9 のチーズを生産する工場である場合はそれぞれ '1', '2', ..., '9' となる．入力には巣と硬さ 1, 2, ..., N のチーズを生産する工場がそれぞれ 1 つずつある．他のマスは障害物または空き地であることが保証されている．ねずみは全てのチーズを食べられることが保証されている．

出力

すべてのチーズを食べ終えるまでにかかる最短時間（分）を表す整数を 1 行で出力せよ．

入出力例

入力例 1
  

3 3 1
S..
...
..1

出力例 1

4

入力例 2
  

4 5 2
.X..1
....X
.XX.S
.2.X.

出力例 2

12

入力例 3
  

10 10 9
.X...X.S.X
6..5X..X1X
...XXXX..X
X..9X...X.
8.X2X..X3X
...XX.X4..
XX....7X..
X..X..XX..
X...X.XX..
..X.......

出力例 3

91

問題文と自動審判に使われるデータは、情報オリンピック日本委員会が作成し公開している問題文と採点用テストデータです。



Sample input:
3 3 1
S..
...
..1


Sample output:
4

Submission status: Accepted

Solution code:
import copy
def bfs(count, x, y, cheese):
    queue = [(count,x,y)]
    tempVisited = copy.deepcopy(visited)
    tempVisited[x][y] = True
    
    while len(queue)>0:
        tempc,tempx,tempy = queue.pop(0)
        if geo[tempx][tempy] == cheese:
            return tempc,tempx,tempy
        for i in range(4):
            neox = tempx+dx[i]
            neoy = tempy+dy[i]
            if canGoTo(neox,neoy, tempVisited):
                if (tempc+1,neox,neoy) not in queue:
                    queue.append((tempc+1,neox,neoy))
                    tempVisited[neox][neoy]=True
    return (-1,-1,-1)

def canGoTo(x,y,tempVisited):
    if 0<=x<H and 0<=y<W:
        return not tempVisited[x][y]
    return False

dx = [0,1,0,-1]
dy = [-1,0,1,0]

data = input().split(' ')
H,W,N = map(int, data)

#maps
geo = [[None for i in range(W)] for j in range(H)]
visited = [[False for i in range(W)] for j in range(H)]

x,y=-1,-1
for i in range(H):
    line = input()
    for j in range(W):
        p = line[j:j+1]
        geo[i][j] = p
        if p == 'X':
            visited[i][j] = True
        elif p == 'S':
            x,y, = i,j
            
count = 0
for n in range(1,N+1):
    count,x,y = bfs(count,x,y,str(n))
print(count)

Submission status: Accepted

Solution code:
import copy
import queue
def bfs(count, x, y, cheese):
    q = queue.Queue()
    q.put((count,x,y))
    tempVisited = copy.deepcopy(visited)
    tempVisited[x][y] = True
    
    while q.qsize()>0:
        tempc,tempx,tempy = q.get(0)
        if geo[tempx][tempy] == cheese:
            return tempc,tempx,tempy
        for i in range(4):
            neox = tempx+dx[i]
            neoy = tempy+dy[i]
            if canGoTo(neox,neoy, tempVisited):
                #if (tempc+1,neox,neoy) not in q:
                q.put((tempc+1,neox,neoy))
                tempVisited[neox][neoy]=True
    return (-1,-1,-1)

def canGoTo(x,y,tempVisited):
    if 0<=x<H and 0<=y<W:
        return not tempVisited[x][y]
    return False

dx = [0,1,0,-1]
dy = [-1,0,1,0]

data = input().split(' ')
H,W,N = map(int, data)

#maps
geo = [[None for i in range(W)] for j in range(H)]
visited = [[False for i in range(W)] for j in range(H)]

x,y=-1,-1
for i in range(H):
    line = input()
    for j in range(W):
        p = line[j:j+1]
        geo[i][j] = p
        if p == 'X':
            visited[i][j] = True
        elif p == 'S':
            x,y, = i,j
            
count = 0
for n in range(1,N+1):
    count,x,y = bfs(count,x,y,str(n))
print(count)

Submission status: Accepted

Solution code:
import copy
import queue
def bfs(count, x, y, cheese):
    q = queue.Queue()
    q.put((count,x,y))
    tempVisited = copy.deepcopy(visited)
    tempVisited[x][y] = True
    
    while q.qsize()>0:
        tempc,tempx,tempy = q.get()
        if geo[tempx][tempy] == cheese:
            return tempc,tempx,tempy
        for i in range(4):
            neox = tempx+dx[i]
            neoy = tempy+dy[i]
            if canGoTo(neox,neoy, tempVisited):
                #if (tempc+1,neox,neoy) not in q:
                q.put((tempc+1,neox,neoy))
                tempVisited[neox][neoy]=True
    return (-1,-1,-1)

def canGoTo(x,y,tempVisited):
    if 0<=x<H and 0<=y<W:
        return not tempVisited[x][y]
    return False

dx = [0,1,0,-1]
dy = [-1,0,1,0]

data = input().split(' ')
H,W,N = map(int, data)

#maps
geo = [[None for i in range(W)] for j in range(H)]
visited = [[False for i in range(W)] for j in range(H)]

x,y=-1,-1
for i in range(H):
    line = input()
    for j in range(W):
        p = line[j:j+1]
        geo[i][j] = p
        if p == 'X':
            visited[i][j] = True
        elif p == 'S':
            x,y, = i,j
            
count = 0
for n in range(1,N+1):
    count,x,y = bfs(count,x,y,str(n))
print(count)

Submission status: Accepted

Solution code:
import copy
from collections import deque
def bfs(count, x, y, cheese):
    q = deque()
    q.append((count,x,y))
    tempVisited = copy.deepcopy(visited)
    tempVisited[x][y] = True
    
    while len(q)>0:
        tempc,tempx,tempy = q.popleft()
        if geo[tempx][tempy] == cheese:
            return tempc,tempx,tempy
        for i in range(4):
            neox = tempx+dx[i]
            neoy = tempy+dy[i]
            if canGoTo(neox,neoy, tempVisited):
                if (tempc+1,neox,neoy) not in q:
                    q.append((tempc+1,neox,neoy))
                    tempVisited[neox][neoy]=True
    return (-1,-1,-1)

def canGoTo(x,y,tempVisited):
    if 0<=x<H and 0<=y<W:
        return not tempVisited[x][y]
    return False

dx = [0,1,0,-1]
dy = [-1,0,1,0]

data = input().split(' ')
H,W,N = map(int, data)

#maps
geo = [[None for i in range(W)] for j in range(H)]
visited = [[False for i in range(W)] for j in range(H)]

x,y=-1,-1
for i in range(H):
    line = input()
    for j in range(W):
        p = line[j:j+1]
        geo[i][j] = p
        if p == 'X':
            visited[i][j] = True
        elif p == 'S':
            x,y, = i,j
            
count = 0
for n in range(1,N+1):
    count,x,y = bfs(count,x,y,str(n))
print(count)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(100000000)

moves = [(0, -1), (0, 1), (-1, 0), (1, 0)]


def search(dataset):
    min_time = 0
    mouse = 1
    gx, gy = get_start(dataset)
    for i in xrange(N):
        gx, gy, min_time_tmp = bfs(dataset, (gx, gy), mouse)
        mouse += 1
        min_time += min_time_tmp
    print min_time


def bfs(dataset, start, mouse):
    INF = 10000000
    min_time = [[INF for j in xrange(W)] for i in xrange(H)]
    min_time[start[0]][start[1]] = 0
    queue = [start]

    while len(queue) != 0:
        dx, dy = queue.pop(0)
        for i, j in moves:
            nx = dx + i
            ny = dy + j
            if 0 <= nx < H and 0 <= ny < W and dataset[nx][ny] != 'X' and min_time[nx][ny] == INF:
                cell = dataset[nx][ny]
            else:
                continue
            if type(cell) is int:
                if mouse == int(cell):
                    min_time[nx][ny] = min_time[dx][dy] + 1
                    return nx, ny, min_time[nx][ny]
            min_time[nx][ny] = min_time[dx][dy] + 1
            queue.append((nx, ny))


def get_start(dataset):
    for i in xrange(H):
        rows = dataset[i]
        for j in xrange(W):
            cell = rows[j]
            if cell == 'S':
                return i, j


dataset = []
while True:
    line = raw_input().rstrip().split()
    if len(line) == 3:
        H, W, N = map(int, line)
    else:
        row = []
        for e in line[0]:
            if e.isdigit():
                row.append(int(e))
            else:
                row.append(e)
        dataset.append(row)
    if len(dataset) == H:
        search(dataset)
        break

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(100000000)
 
moves = [(0, -1), (0, 1), (-1, 0), (1, 0)]
 
 
def search(dataset):
    min_time = 0
    mouse = 1
    gx, gy = get_start(dataset)
    for i in xrange(N):
        gx, gy, min_time_tmp = bfs(dataset, (gx, gy), mouse)
        mouse += 1
        min_time += min_time_tmp
    print min_time
 
 
def bfs(dataset, start, mouse):
    INF = 10000000
    min_time = [[INF for j in xrange(W)] for i in xrange(H)]
    min_time[start[0]][start[1]] = 0
    queue = [start]
 
    while len(queue) != 0:
        dx, dy = queue.pop(0)
        for i, j in moves:
            nx = dx + i
            ny = dy + j
            if 0 <= nx < H and 0 <= ny < W and dataset[nx][ny] != 'X' and min_time[nx][ny] == INF:
                cell = dataset[nx][ny]
            else:
                continue
            if type(cell) is int:
                if mouse == int(cell):
                    min_time[nx][ny] = min_time[dx][dy] + 1
                    return nx, ny, min_time[nx][ny]
            min_time[nx][ny] = min_time[dx][dy] + 1
            queue.append((nx, ny))
 
 
def get_start(dataset):
    for i in xrange(H):
        rows = dataset[i]
        for j in xrange(W):
            cell = rows[j]
            if cell == 'S':
                return i, j
 
 
dataset = []
while True:
    line = raw_input().rstrip().split()
    if len(line) == 3:
        H, W, N = map(int, line)
    else:
        row = []
        for e in line[0]:
            if e.isdigit():
                row.append(int(e))
            else:
                row.append(e)
        dataset.append(row)
    if len(dataset) == H:
        search(dataset)
        break

Submission status: Accepted

Solution code:

def getStart(field):
    search_field = field[1:]     # cut the first [H,W,N] for min_path matrix
    for y in range(len(search_field)):
        for x in range(len(search_field[0])):
            if search_field[y][x] == "S":
                return x,y+1


def bfs(field,start_x,start_y,goal_N):
    direction = [[-1,0],[1,0],[0,-1],[0,1]]
    gotten_cheese = 1
    distance = 0
    que = []
    que.append([start_x,start_y,gotten_cheese,distance])
    INF = 1
    min_path = [[INF for j in range(field[0][1])] for i in range(field[0][0])]
    while len(que) != 0:
        current = que.pop(0)
        for d in direction:
            nx = current[0] + d[0]
            ny = current[1] + d[1]
            if 0 <= nx < field[0][1] and 1 <= ny < field[0][0]+1 and field[ny][nx] != "X" and min_path[ny-1][nx] == INF:
                if field[ny][nx] == current[2]: # at the same cheese-power number
                    if field[ny][nx] == goal_N: # goal
                        print(current[3]+1)
                        return
                    else: # not goal, but could eat cheese
                        que = []
                        que.append([nx,ny,current[2]+1,current[3]+1])
                        min_path = [[INF for j in range(field[0][1])] for i in range(field[0][0])]
                        break
                else:
                    que.append([nx,ny,current[2],current[3]+1])
                    min_path[ny-1][nx] = 0


def main(field):

    # field = [[10,10,9],
    # [".","X",".",".",".","X",".","S",".","X"],
    # [6,".",".",5,"X",".",".","X",1,"X"],
    # [".",".",".","X","X","X","X",".",".","X"],
    # ["X",".",".",9,"X",".",".",".","X","."],
    # [8,".","X",2,"X",".",".","X",3,"X"],
    # [".",".",".","X","X",".","X",4,".","."],
    # ["X","X",".",".",".",".",7,"X",".","."],
    # ["X",".",".","X",".",".","X","X",".","."],
    # ["X",".",".",".","X",".","X","X",".","."],
    # [".",".","X",".",".",".",".",".",".","."]]

    sx,sy = getStart(field)
    bfs(field,sx,sy,field[0][2])

matrix = []
while True:
    row = input().rstrip().split()
    if len(row) == 3:
        re_row = []
        for i in row:
            re_row.append(int(i))
        matrix.append(re_row)
    else:
        re_row = []
        for char in row[0]:
            if char.isdigit():
                re_row.append(int(char))
            else:
                re_row.append(char)
        matrix.append(re_row)
    if len(matrix) == int(matrix[0][0]) + 1:
        main(matrix)
        break

Submission status: Accepted

Solution code:

def getStart(field):
    search_field = field[1:]  
    for y in range(len(search_field)):
        for x in range(len(search_field[0])):
            if search_field[y][x] == "S":
                return x,y+1


def bfs(field,start_x,start_y,goal_N):
    direction = [[-1,0],[1,0],[0,-1],[0,1]]
    gotten_cheese = 1
    distance = 0
    que = []
    que.append([start_x,start_y,gotten_cheese,distance])
    INF = 1
    min_path = [[INF for j in range(field[0][1])] for i in range(field[0][0])]
    while len(que) != 0:
        current = que.pop(0)
        for d in direction:
            nx = current[0] + d[0]
            ny = current[1] + d[1]
            if 0 <= nx < field[0][1] and 1 <= ny < field[0][0]+1 and field[ny][nx] != "X" and min_path[ny-1][nx] == INF:
                if field[ny][nx] == current[2]: 
                    if field[ny][nx] == goal_N: 
                        print(current[3]+1)
                        return
                    else: # not goal, but could eat cheese
                        que = []
                        que.append([nx,ny,current[2]+1,current[3]+1])
                        min_path = [[INF for j in range(field[0][1])] for i in range(field[0][0])]
                        break
                else:
                    que.append([nx,ny,current[2],current[3]+1])
                    min_path[ny-1][nx] = 0


def main(field):

    sx,sy = getStart(field)
    bfs(field,sx,sy,field[0][2])

matrix = []
while True:
    row = input().rstrip().split()
    if len(row) == 3:
        re_row = []
        for i in row:
            re_row.append(int(i))
        matrix.append(re_row)
    else:
        re_row = []
        for char in row[0]:
            if char.isdigit():
                re_row.append(int(char))
            else:
                re_row.append(char)
        matrix.append(re_row)
    if len(matrix) == int(matrix[0][0]) + 1:
        main(matrix)
        break

Submission status: Accepted

Solution code:

def getStart(field):
    search_field = field[1:]
    for y in range(len(search_field)):
        for x in range(len(search_field[0])):
            if search_field[y][x] == "S":
                return x,y+1


def bfs(field,start_x,start_y,goal_N):
    direction = [[-1,0],[1,0],[0,-1],[0,1]]
    gotten_cheese = 1
    distance = 0
    que = []
    que.append([start_x,start_y,gotten_cheese,distance])
    INF = 1
    min_path = [[INF for j in range(field[0][1])] for i in range(field[0][0])]
    while len(que) != 0:
        current = que.pop(0)
        for d in direction:
            nx = current[0] + d[0]
            ny = current[1] + d[1]
            if 0 <= nx < field[0][1] and 1 <= ny < field[0][0]+1 and field[ny][nx] != "X" and min_path[ny-1][nx] == INF:
                if field[ny][nx] == current[2]:
                    if field[ny][nx] == goal_N:
                        print(current[3]+1)
                        return
                    else:
                        que = []
                        que.append([nx,ny,current[2]+1,current[3]+1])
                        min_path = [[INF for j in range(field[0][1])] for i in range(field[0][0])]
                        break
                else:
                    que.append([nx,ny,current[2],current[3]+1])
                    min_path[ny-1][nx] = 0


def main(field):
    sx,sy = getStart(field)
    bfs(field,sx,sy,field[0][2])

matrix = []
while True:
    row = input().rstrip().split()
    if len(row) == 3:
        re_row = []
        for i in row:
            re_row.append(int(i))
        matrix.append(re_row)
    else:
        re_row = []
        for char in row[0]:
            if char.isdigit():
                re_row.append(int(char))
            else:
                re_row.append(char)
        matrix.append(re_row)
    if len(matrix) == int(matrix[0][0]) + 1:
        main(matrix)
        break

Submission status: Accepted

Solution code:

def getStart(field):
    search_field = field[1:]     # cut the first [H,W,N] for min_path matrix
    for y in range(len(search_field)):
        for x in range(len(search_field[0])):
            if search_field[y][x] == "S":
                return x,y+1


def bfs(field,start_x,start_y,goal_N):
    direction = [[-1,0],[1,0],[0,-1],[0,1]]
    gotten_cheese = 1
    distance = 0
    que = []
    que.append([start_x,start_y,gotten_cheese,distance])
    INF = 1
    min_path = [[INF for j in range(field[0][1])] for i in range(field[0][0])]
    while len(que) != 0:
        current = que.pop(0)
        for d in direction:
            nx = current[0] + d[0]
            ny = current[1] + d[1]
            if 0 <= nx < field[0][1] and 1 <= ny < field[0][0]+1 and field[ny][nx] != "X" and min_path[ny-1][nx] == INF:
                if field[ny][nx] == current[2]: # at the same cheese-power number
                    if field[ny][nx] == goal_N: # goal
                        print(current[3]+1)
                        return
                    else: # not goal, but could eat cheese
                        que = []
                        que.append([nx,ny,current[2]+1,current[3]+1])
                        min_path = [[INF for j in range(field[0][1])] for i in range(field[0][0])]
                        break
                else:
                    que.append([nx,ny,current[2],current[3]+1])
                    min_path[ny-1][nx] = 0


def main(field):

    # field = [[10,10,9],
    # [".","X",".",".",".","X",".","S",".","X"],
    # [6,".",".",5,"X",".",".","X",1,"X"],
    # [".",".",".","X","X","X","X",".",".","X"],
    # ["X",".",".",9,"X",".",".",".","X","."],
    # [8,".","X",2,"X",".",".","X",3,"X"],
    # [".",".",".","X","X",".","X",4,".","."],
    # ["X","X",".",".",".",".",7,"X",".","."],
    # ["X",".",".","X",".",".","X","X",".","."],
    # ["X",".",".",".","X",".","X","X",".","."],
    # [".",".","X",".",".",".",".",".",".","."]]

    sx,sy = getStart(field)
    bfs(field,sx,sy,field[0][2])

# field = []
# while True:
#     row = input().split()
#     for i in range(len(row)):
#         try:
#             row[i] = int(row[i])
#         except:
#             continue
#     field.append(row)
#     if len(field) == field[0][0] + 1:
#         main(field)
#         break



matrix = []
while True:
    row = input().rstrip().split()
    if len(row) == 3:
        re_row = []
        for i in row:
            re_row.append(int(i))
        matrix.append(re_row)
    else:
        re_row = []
        for char in row[0]:
            if char.isdigit():
                re_row.append(int(char))
            else:
                re_row.append(char)
        matrix.append(re_row)
    if len(matrix) == int(matrix[0][0]) + 1:
        main(matrix)
        break

Submission status: Accepted

Solution code:

def getStart(field):
    search_field = field[1:]     # cut the first [H,W,N] for min_path matrix
    for y in range(len(search_field)):
        for x in range(len(search_field[0])):
            if search_field[y][x] == "S":
                return x,y+1


def bfs(field,start_x,start_y,goal_N):
    direction = [[-1,0],[1,0],[0,-1],[0,1]]
    gotten_cheese = 1
    distance = 0
    que = []
    que.append([start_x,start_y])
    INF = 1000000
    min_path = [[INF] * field[0][1] for i in range(field[0][0])]
    min_path[start_y-1][start_x] = 0
    while len(que) != 0:
        current = que.pop(0)
        for d in direction:
            nx = current[0] + d[0]
            ny = current[1] + d[1]
            if 0 <= nx < field[0][1] and 1 <= ny < field[0][0]+1 and field[ny][nx] != "X" and min_path[ny-1][nx] == INF:
                min_path[ny-1][nx] = min_path[current[1]-1][current[0]] + 1
                if field[ny][nx] == gotten_cheese: # at the same cheese-power number
                    distance += min_path[ny-1][nx]
                    if field[ny][nx] == goal_N: # goal
                        print(distance)
                        return
                    else: # not goal, but could eat cheese
                        que = []
                        que.append([nx,ny])
                        gotten_cheese += 1
                        min_path = [[INF] * field[0][1] for i in range(field[0][0])]
                        min_path[ny-1][nx] = 0
                        break
                else:
                    que.append([nx,ny])


def main(field):
    sx,sy = getStart(field)
    bfs(field,sx,sy,field[0][2])

# field = [[10,10,9],
# [".","X",".",".",".","X",".","S",".","X"],
# [6,".",".",5,"X",".",".","X",1,"X"],
# [".",".",".","X","X","X","X",".",".","X"],
# ["X",".",".",9,"X",".",".",".","X","."],
# [8,".","X",2,"X",".",".","X",3,"X"],
# [".",".",".","X","X",".","X",4,".","."],
# ["X","X",".",".",".",".",7,"X",".","."],
# ["X",".",".","X",".",".","X","X",".","."],
# ["X",".",".",".","X",".","X","X",".","."],
# [".",".","X",".",".",".",".",".",".","."]]
#
# main(field)

matrix = []
while True:
    row = input().rstrip().split()
    if len(row) == 3:
        re_row = []
        for i in row:
            re_row.append(int(i))
        matrix.append(re_row)
    else:
        re_row = []
        for char in row[0]:
            if char.isdigit():
                re_row.append(int(char))
            else:
                re_row.append(char)
        matrix.append(re_row)
    if len(matrix) == int(matrix[0][0]) + 1:
        main(matrix)
        break

Submission status: Accepted

Solution code:
from collections import deque

def getStart(field):
    search_field = field[1:]     # cut the first [H,W,N] for min_path matrix
    for y in range(len(search_field)):
        for x in range(len(search_field[0])):
            if search_field[y][x] == "S":
                return x,y+1


def bfs(field,start_x,start_y,goal_N):
    direction = [[-1,0],[1,0],[0,-1],[0,1]]
    gotten_cheese = 1
    distance = 0
    que = []
    que.append([start_x,start_y])
    INF = 1000000
    min_path = [[INF] * field[0][1] for i in range(field[0][0])]
    min_path[start_y-1][start_x] = 0
    while len(que) != 0:
        current = que.pop(0)
        for d in direction:
            nx = current[0] + d[0]
            ny = current[1] + d[1]
            if 0 <= nx < field[0][1] and 1 <= ny < field[0][0]+1 and field[ny][nx] != "X" and min_path[ny-1][nx] == INF:
                min_path[ny-1][nx] = min_path[current[1]-1][current[0]] + 1
                if field[ny][nx] == gotten_cheese: # at the same cheese-power number
                    distance += min_path[ny-1][nx]
                    if field[ny][nx] == goal_N: # goal
                        print(distance)
                        return
                    else: # not goal, but could eat cheese
                        que = []
                        que.append([nx,ny])
                        gotten_cheese += 1
                        min_path = [[INF] * field[0][1] for i in range(field[0][0])]
                        min_path[ny-1][nx] = 0
                        break
                else:
                    que.append([nx,ny])


def main(field):
    sx,sy = getStart(field)
    bfs(field,sx,sy,field[0][2])

# field = [[10,10,9],
# [".","X",".",".",".","X",".","S",".","X"],
# [6,".",".",5,"X",".",".","X",1,"X"],
# [".",".",".","X","X","X","X",".",".","X"],
# ["X",".",".",9,"X",".",".",".","X","."],
# [8,".","X",2,"X",".",".","X",3,"X"],
# [".",".",".","X","X",".","X",4,".","."],
# ["X","X",".",".",".",".",7,"X",".","."],
# ["X",".",".","X",".",".","X","X",".","."],
# ["X",".",".",".","X",".","X","X",".","."],
# [".",".","X",".",".",".",".",".",".","."]]
#
# main(field)

matrix = []
while True:
    row = input().rstrip().split()
    if len(row) == 3:
        re_row = []
        for i in row:
            re_row.append(int(i))
        matrix.append(re_row)
    else:
        re_row = []
        for char in row[0]:
            if char.isdigit():
                re_row.append(int(char))
            else:
                re_row.append(char)
        matrix.append(re_row)
    if len(matrix) == int(matrix[0][0]) + 1:
        main(matrix)
        break

Submission status: Accepted

Solution code:
from collections import deque

def getStart(field):
    search_field = field[1:]     # cut the first [H,W,N] for min_path matrix
    for y in range(len(search_field)):
        for x in range(len(search_field[0])):
            if search_field[y][x] == "S":
                return x,y+1


def bfs(field,start_x,start_y,goal_N):
    direction = [[-1,0],[1,0],[0,-1],[0,1]]
    gotten_cheese = 1
    distance = 0
    que = []
    que.append([start_x,start_y])
    INF = 1000000
    min_path = [[INF] * field[0][1] for i in range(field[0][0])]
    min_path[start_y-1][start_x] = 0
    while len(que) != 0:
        current = que.pop(0)
        for d in direction:
            nx = current[0] + d[0]
            ny = current[1] + d[1]
            if 0 <= nx < field[0][1] and 1 <= ny < field[0][0]+1 and field[ny][nx] != "X" and min_path[ny-1][nx] == INF:
                min_path[ny-1][nx] = min_path[current[1]-1][current[0]] + 1
                if field[ny][nx] == gotten_cheese:
                    distance += min_path[ny-1][nx]
                    if field[ny][nx] == goal_N: # goal
                        print(distance)
                        return
                    else: # not goal, but could eat cheese
                        que = []
                        que.append([nx,ny])
                        gotten_cheese += 1
                        min_path = [[INF] * field[0][1] for i in range(field[0][0])]
                        min_path[ny-1][nx] = 0
                        break
                else:
                    que.append([nx,ny])


def main(field):
    sx,sy = getStart(field)
    bfs(field,sx,sy,field[0][2])

matrix = []
while True:
    row = input().rstrip().split()
    if len(row) == 3:
        re_row = []
        for i in row:
            re_row.append(int(i))
        matrix.append(re_row)
    else:
        re_row = []
        for char in row[0]:
            if char.isdigit():
                re_row.append(int(char))
            else:
                re_row.append(char)
        matrix.append(re_row)
    if len(matrix) == int(matrix[0][0]) + 1:
        main(matrix)
        break

Submission status: Accepted

Solution code:

def bfs(field,H,W,start_x,start_y,tmp_N):
    direction = [[-1,0],[1,0],[0,-1],[0,1]]
    que = []
    que.append([start_x,start_y])
    INF = 1000000
    min_path = [[INF] * W for i in range(H)]
    min_path[start_y][start_x] = 0
    while len(que) != 0:
        current = que.pop(0)
        for d in direction:
            nx = current[0] + d[0]
            ny = current[1] + d[1]
            if 0 <= nx < W and 0 <= ny < H and field[ny][nx] != "X" and min_path[ny][nx] == INF:
                min_path[ny][nx] = min_path[current[1]][current[0]] + 1
                if field[ny][nx] == tmp_N: # at the same cheese-power number
                    return nx,ny,min_path[ny][nx]
                else:
                    que.append([nx,ny])

def getField():
    matrix = []
    first = input().strip()
    H,W,N = map(int,first.split())
    for i in range(H):
        row = list(input().strip())
        for j in range(W):
            if row[j].isdigit():
                row[j] = int(row[j])
        matrix.append(row)
    return matrix,H,W,N

def getStart(field):
    for y in range(len(field)):
        for x in range(len(field[0])):
            if field[y][x] == "S":
                return x,y

def main():
    matrix,H,W,N = getField()
    sx,sy = getStart(matrix)
    distance = 0
    for k in range(N):
        if k != 0:
            tmp_x,tmp_y,tmp_dist = bfs(matrix,H,W,tmps[0],tmps[1],k+1)
            distance += tmp_dist
            tmps = [tmp_x,tmp_y]
        else:
            tmp_x,tmp_y,tmp_dist = bfs(matrix,H,W,sx,sy,k+1)
            distance += tmp_dist
            tmps = [tmp_x,tmp_y]
    print(distance)


if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
moves = [(0, -1), (0, 1), (-1, 0), (1, 0)]
 
 
def search(dataset):
    min_time = 0
    mouse = 1
    gx, gy = get_start(dataset)
    for i in range(N):
        gx, gy, min_time_tmp = bfs(dataset, (gx, gy), mouse)
        mouse += 1
        min_time += min_time_tmp
    print(min_time)
 
 
def bfs(dataset, start, mouse):
    INF = 10000000
    min_time = [[INF for j in range(W)] for i in range(H)]
    min_time[start[0]][start[1]] = 0
    queue = [start]
 
    while len(queue) != 0:
        dx, dy = queue.pop(0)
        for i, j in moves:
            nx = dx + i
            ny = dy + j
            if 0 <= nx < H and 0 <= ny < W and dataset[nx][ny] != 'X' and min_time[nx][ny] == INF:
                cell = dataset[nx][ny]
            else:
                continue
            if type(cell) is int:
                if mouse == int(cell):
                    min_time[nx][ny] = min_time[dx][dy] + 1
                    return nx, ny, min_time[nx][ny]
            min_time[nx][ny] = min_time[dx][dy] + 1
            queue.append((nx, ny))
 
 
def get_start(dataset):
    for i in range(H):
        rows = dataset[i]
        for j in range(W):
            cell = rows[j]
            if cell == 'S':
                return i, j
 
 
dataset = []
while True:
    line = input().rstrip().split()
    if len(line) == 3:
        H, W, N = map(int, line)
    else:
        row = []
        for e in line[0]:
            if e.isdigit():
                row.append(int(e))
            else:
                row.append(e)
        dataset.append(row)
    if len(dataset) == H:
        search(dataset)
        break

Submission status: Accepted

Solution code:
def bfs(field,H,W,start_x,start_y,tmp_N):
    direction = [[-1,0],[1,0],[0,-1],[0,1]]
    que = []
    que.append([start_x,start_y])
    INF = 1000000
    min_path = [[INF] * W for i in range(H)]
    min_path[start_y][start_x] = 0
    while len(que) != 0:
        current = que.pop(0)
        for d in direction:
            nx = current[0] + d[0]
            ny = current[1] + d[1]
            if 0 <= nx < W and 0 <= ny < H and field[ny][nx] != "X" and min_path[ny][nx] == INF:
                min_path[ny][nx] = min_path[current[1]][current[0]] + 1
                if field[ny][nx] == tmp_N:
                    return nx,ny,min_path[ny][nx]
                else:
                    que.append([nx,ny])

def getField():
    matrix = []
    first = input().strip()
    H,W,N = map(int,first.split())
    for i in range(H):
        row = list(input().strip())
        for j in range(W):
            if row[j].isdigit():
                row[j] = int(row[j])
        matrix.append(row)
    return matrix,H,W,N

def getStart(field):
    for y in range(len(field)):
        for x in range(len(field[0])):
            if field[y][x] == "S":
                return x,y

def main():
    matrix,H,W,N = getField()
    sx,sy = getStart(matrix)
    distance = 0
    for k in range(N):
        if k != 0:
            tmp_x,tmp_y,tmp_dist = bfs(matrix,H,W,tmps[0],tmps[1],k+1)
            distance += tmp_dist
            tmps = [tmp_x,tmp_y]
        else:
            tmp_x,tmp_y,tmp_dist = bfs(matrix,H,W,sx,sy,k+1)
            distance += tmp_dist
            tmps = [tmp_x,tmp_y]
    print(distance)

if __name__=='__main__':
    main()