Go: ///
// File:  0558.go
// Author: ymiyamoto
//
// Created on Sun Mar  4 20:58:45 2018
//
package main

import (
	"fmt"
	"strconv"
	"strings"
)

type pos struct {
	x, y int
}

var H, W, N int
var graph [][]string

func wfs(p pos, index int) (int, pos) {
	var q []pos
	dists := make([][]int, H)
	for i := range dists {
		dists[i] = make([]int, W)
	}

	q = append(q, p)
	for len(q) > 0 {
		p := q[0]
		dist := dists[p.x][p.y]
		q = q[1:]

		for _, d := range []pos{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} {
			x := p.x + d.x
			y := p.y + d.y
			if 0 <= x && x < H && 0 <= y && y < W && graph[x][y] != "X" && dists[x][y] == 0 {
				dists[x][y] = dist + 1
				q = append(q, pos{x, y})
			}
		}
	}

	for i := range graph {
		for j := range graph[i] {
			if graph[i][j] == strconv.Itoa(index) {
				return dists[i][j], pos{i, j}
			}
		}
	}

	panic("not found")
}

func main() {
	fmt.Scan(&H, &W, &N)

	var start pos

	graph = make([][]string, H)
	for i := range graph {
		var s string
		fmt.Scan(&s)
		graph[i] = strings.Split(s, "")
		for j := range graph[i] {
			if graph[i][j] == "S" {
				start.x = i
				start.y = j
			}
		}
	}

	count := 0
	for i := 1; i <= N; i++ {
		c, s := wfs(start, i)
		start = s
		count += c
	}

	fmt.Println(count)
}

Python: import queue

# directions
x_dir = [0, 1, 0, -1]
y_dir = [1, 0, -1, 0]


# initialization visited maps
def init_visited_maps(h, w):
    return [[True for i in range(w)] for j in range(h)]


# bfs algorithm
def bfs(h, w, cheese, maps, sx, sy, moves):
    que = queue.Queue()
    que.put((moves, sx, sy))

    visited = init_visited_maps(h, w)
    visited[sy][sx] = False

    while que.qsize() > 0:
        c_moves, c_x, c_y = que.get()
        if maps[c_y][c_x] == cheese:
            return (c_moves, c_x, c_y)

        for i in range(4):
            n_x = c_x + x_dir[i]
            n_y = c_y + y_dir[i]

            if(0 <= n_x < w and 0 <= n_y < h and visited[n_y][n_x] and maps[n_y][n_x] != 'X'):
                que.put((c_moves+1, n_x, n_y))
                visited[n_y][n_x] = False

    return (-1, -1, -1)


# simulate mouse
def simulate(h, w, n, maps, sx, sy):
    moves = 0
    x, y = sx, sy

    for i in range(1, n+1, 1):
        moves, x, y = bfs(h, w, str(i), maps, x, y, moves)

    return str(moves)


# main function
def main():
    str = (input()).split()

    H = int(str[0])
    W = int(str[1])
    N = int(str[2])

    maps = []
    sx, sy = 0, 0
    for i in range(H):
        maps.append(input())
        for j in range(W):
            if maps[i][j] == 'S':
                sx, sy = j, i

    print(simulate(H, W, N, maps, sx, sy))


if __name__ == '__main__':
    main()

Python: def v():
 from collections import deque
 H,W,N=map(int,input().split())
 e='X'*(W+2)
 M=e+''.join('X'+input()+'X'for _ in[0]*H)+e
 m=(1,-1,W+2,-W-2)
 def f(s,g):
  p,t=s,0
  q=deque()
  b=[1]*len(M);b[s]=0
  while 1:
   for d in m:
    n=p+d
    if'X'!=M[n]and b[n]:
     if M[n]==g:return(n,t+1)
     b[n]=0;q.append([n,t+1])
   p,t=q.popleft()
 s=M.find('S')
 a=0
 for i in range(1,N+1):
  s,t=f(s,str(i))
  a+=t
 print(a)
v()

Python: import sys

file_input = sys.stdin

H, W, N = map(int, file_input.readline().split())

town_map = file_input.read()

start_index = town_map.index('S')

mouse = [start_index, 0]
# position, elapsed time

from collections import deque

for goal in range(1, N + 1):
    q = deque()
    unvisited = [True] * len(town_map)
    unvisited[mouse[0]] = False
    goal = str(goal)
    while True:
        cur_pos = mouse[0]
        
        ew_pos = cur_pos % (W + 1)
        if ew_pos < (W - 1):
            next_pos = cur_pos + 1
            lot = town_map[next_pos]
            if lot != 'X' and unvisited[next_pos]:
                if lot == goal:
                    mouse = [next_pos, mouse[1] + 1]
                    break
                else:
                    m = [next_pos, mouse[1] + 1]
                    unvisited[next_pos] = False
                    q.append(m)
        if ew_pos > 0:
            next_pos = cur_pos - 1
            lot = town_map[next_pos]
            if lot != 'X' and unvisited[next_pos]:
                if lot == goal:
                    mouse = [next_pos, mouse[1] + 1]
                    break
                else:
                    m = [next_pos, mouse[1] + 1]
                    unvisited[next_pos] = False
                    q.append(m)
        
        ns_pos = cur_pos // (W + 1)
        if ns_pos < (H - 1):
            next_pos = cur_pos + W + 1
            lot = town_map[next_pos]
            if lot != 'X' and unvisited[next_pos]:
                if lot == goal:
                    mouse = [next_pos, mouse[1] + 1]
                    break
                else:
                    m = [next_pos, mouse[1] + 1]
                    unvisited[next_pos] = False
                    q.append(m)
        if ns_pos > 0:
            next_pos = cur_pos - W - 1
            lot = town_map[next_pos]
            if lot != 'X' and unvisited[next_pos]:
                if lot == goal:
                    mouse = [next_pos, mouse[1] + 1]
                    break
                else:
                    m = [next_pos, mouse[1] + 1]
                    unvisited[next_pos] = False
                    q.append(m)
        mouse = q.popleft()

print(mouse[1])

Python: from queue import Queue
from collections import defaultdict
try:
    d = [[1, 0], [-1, 0], [0, 1], [0, -1]]
    H, W, N = map(int, input().split())
    G = []
    sx = sy = 0
    for i in range(H):
        G.append(input())
        for j, c in enumerate(G[i]):
            if c == 'S':
                sx, sy = i, j

    Q = Queue()
    Q.put((sx, sy, 0))
    visited = defaultdict(lambda: defaultdict(lambda: 0))
    # visited = [[False for _ in range(W)] for _ in range(H)]
    visited[sx][sy] = True
    target = 1

    while not Q.empty():
        x, y, step = Q.get()
        if G[x][y] == str(target):
            # visited = [[False for _ in range(W)] for _ in range(H)]
            # visited.clear()
            target += 1
            visited[x][y] = target
            while not Q.empty():
                Q.get()
            if target == N + 1:
                print(step)
                break
        for dx, dy in d:
            nx, ny = x + dx, y + dy
            if 0 <= nx < H and 0 <= ny < W and G[nx][ny] != 'X':
                if visited[nx][ny] != target:
                    visited[nx][ny] = target
                    Q.put((nx, ny, step + 1))

except BaseException as e:
    print(e)