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: from sys import stdin
from collections import deque


def grid2adj(arr_grid,direction=4):
    def cand(i,j,direction):
        if direction == 4:
            return [[i-1,j],[i+1,j],[i,j-1],[i,j+1]]
        elif direction == 8:
            return [[i-1,j],[i+1,j],[i,j-1],[i,j+1],
                    [i-1,j-1],[i-1,j+1],[i+1,j-1],[i+1,j+1]]
        else:
            print('Error')
    
    M,N = len(arr_grid),len(arr_grid[0])
    arr_con = [[] for i in range(M*N)]
    for i in range(M):
        for j in range(N):
            v = i*N+j
            for _cand in cand(i,j,direction):
                if 0<=_cand[0]<M and 0<=_cand[1]<N:
                    next_v = _cand[0]*N+_cand[1]
                    arr_con[v].append(next_v)
    arr_val = sum(arr_grid,[])

    return arr_con, arr_val


class BFS():
    def __init__(self, con, val=None):
        # 隣接リスト表現
        self.con = con
        self.val = val
        self.N = len(self.con)
        # 始点からの距離
        self.dist = [-1]*self.N
        self.que = deque()

    def clear(self):
        self.dist = [-1]*self.N
        self.que = deque()

    def bfs(self, start_v, sach_v):
        # 初期条件(0-indexed)
        self.dist[start_v] = 0
        self.que.append(start_v)

        while len(self.que)>0:
            v = self.que.popleft()
            for next_v in self.con[v]:
                if self.dist[next_v] != -1:
                    continue
                if self.val[next_v] == 'X':
                    continue
                self.dist[next_v] = self.dist[v] + 1
                self.que.append(next_v)
                if self.val[next_v] == sach_v:
                    return self.dist[next_v]


if __name__ == "__main__":
    _in = [_.rstrip() for _ in stdin.readlines()]
    H,W,N   = list(map(int,_in[0].split(' ')))  # type:list(int)
    graph = []
    for i in range(H):
        _ = list(_in[i+1])  # type:list(str)
        graph.append(_)
    # vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    g_con, g_val = grid2adj(graph)
    bfs = BFS(g_con,g_val)

    cnt = 0
    start_v_arr = ['S']+[str(i) for i in range(1,N+1)]
    for i, start_v in enumerate(start_v_arr[:-1]):
        bfs.clear()
        for v,val in enumerate(g_val):
            if val == start_v:
                cnt += bfs.bfs(v,start_v_arr[i+1])
                break
    # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    print(cnt)

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

Python: def v():
 import sys
 from collections import deque
 H,W,N=map(int,input().split())
 e='X'*(W+2)
 M=e+''.join('X'+e[:-1]+'X'for e in sys.stdin)+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)
if'__main__'==__name__:v()

Python: import queue


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


visited = [[True for i in range(1000)] for j in range(1000)]
maps = []

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

    for i in range(h):
        for j in range(w):
            visited[i][j] = (maps[i][j] != 'X')

    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]):
                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, sx, sy):
    moves = 0
    x, y = sx, sy

    #visited = [[True for i in range(w)] for j in range(h)]

    for i in range(1, n+1, 1):
        moves, x, y = bfs(h, w, str(i), 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])

    del str

    #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, sx, sy))


if __name__ == '__main__':
    main()