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

Python: import sys
sys.setrecursionlimit(100000000)


def getStart(field):     # before this, cut the first [H,W,N]
    search_field = field[1:]
    for i in range(len(search_field)):
        for j in range(len(search_field[0])):
            if search_field[i][j] == "S":
                print("start point ({},{})".format(i+1,j))
                return i+1,j

def bfs(field,start_x,start_y,goal_N):
    x_direction = [-1,0,1,0]
    y_direction = [0,-1,0,1]
    gotten_cheese = 1
    distance = 0
    que = []
    que.append([start_x,start_y,gotten_cheese,distance])
    while len(que) != 0:
        current = que.pop(0)
        for xd,yd in zip(x_direction,y_direction):
            nx = current[0] + xd
            ny = current[1] + yd
            if 0 <= nx < field[0][1] and 1 <= ny < field[0][0]+1 and field[ny][nx] != "X":
                if field[ny][nx] == current[2]:
                    if field[ny][nx] == goal_N:
                        print("GOAL",current[3]+1)
                        return
                    else:
                        que.append([nx,ny,current[2]+1,current[3]+1])
                else:
                    que.append([nx,ny,current[2],current[3]+1])

def getField():
    matrix = []
    while True:
        row = input().split()
        if len(row) == 1:
            re_row = []
            for char in row[0]:
                if char.isdigit():
                    re_row.append(int(char))
                else:
                    re_row.append(char)
            matrix.append(re_row)
        else:
            matrix.append(row)
        if len(matrix) == int(matrix[0][0]) + 1:
            break
    return matrix

def main():
    # field = [[4,5,2],
    # [".","X",".",".",1],
    # [".",".",".",".","X"],
    # [".","X","X",".","S"],
    # [".",2,".","X","."]]

    # 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",".",".",".",".",".",".","."]]

    field = getField()

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

main()

Python: import queue
h,w,n = map(int,input().split())
factrys = [None] * (n + 1)
ss = ["X" * (w + 2)]
for i in range(h):
  s = "X" + input() + "X"
  if "S" in s:
    factrys[0] = (i + 1, s.index("S"))
  for j in range(1,n + 1):
    if str(j) in s:
      factrys[j] = (i + 1, s.index(str(j)))
  ss.append(s)
ss.append("X" * (w + 2))
mp = []
que = queue.Queue()
def bfs(i):
  while True:
    (x,y) = que.get()
  #  print(i,x,y)
  #  print(mp[x][y])
    if (x,y) == factrys[i + 1]:
      return mp[x][y]
    count = mp[x][y]
    if ss[x + 1][y] != "X" and mp[x + 1][y] is None:
      mp[x + 1][y] = count + 1
      que.put((x + 1, y))
    if ss[x - 1][y] != "X" and mp[x - 1][y] is None:
      mp[x - 1][y] = count + 1
      que.put((x - 1, y))
    if ss[x][y + 1] != "X" and mp[x][y + 1] is None:
      mp[x][y + 1] = count + 1
      que.put((x, y + 1))
    if ss[x][y - 1] != "X" and mp[x][y - 1] is None:
      mp[x][y - 1] = count + 1
      que.put((x, y - 1))

def bfs_(i):
  for count in range(1000000):
    sz = que.qsize()
    for loop in range(sz):
      (x,y) = que.get()
      if ss[x][y] == "X" or not mp[x][y] is None:
        continue
      if (x,y) == factrys[i + 1]:
        return count
      mp[x][y] = count
      que.put((x + 1, y))
      que.put((x - 1, y))
      que.put((x, y - 1))
      que.put((x, y + 1))

ans = 0
for i in range(n):
  mp = [[None] * (h + 2) for j in range(w + 2)]
  x,y = factrys[i]
  que = queue.Queue()
  mp[x][y] = 0
  que.put((x,y))
  ans += (bfs(i))
print(ans)