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,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] * field[0][1] for i in range(field[0][0])]
    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 < field[0][1] and 0 <= ny < field[0][0] 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,N

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

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


if __name__=='__main__':
    main()

Python: 
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])] #[[INF for j in range(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:
                distance += min_path[current[1]-1][current[0]] + 1
                if field[ny][nx] == gotten_cheese: # at the same cheese-power number
                    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):

    # 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:
        print(matrix)
        main(matrix)
        break

Python: import collections
INF = 10**18
h,w,n = map(int,input().split())
li = [list(input()) for i in range(h)]
num = [0]*9
def bfs(sy,sx,gy,gx):
    d = [[INF]*w for i in range(h)]
    dx = [1,0,-1,0]
    dy = [0,1,0,-1]
    d[sy][sx] = 0
    que = collections.deque([])
    que.append((sy,sx))
    while que:
        y,x = que.popleft()
        for i in range(4):
            ny = y + dy[i]
            nx = x + dx[i]
            if 0<=nx<w and 0<=ny<h:
                if li[ny][nx] != "X" and d[ny][nx] == INF:
                    que.append((ny,nx))
                    d[ny][nx] = d[y][x] + 1
    return d[gy][gx]

for i in range(h):
    for j in range(w):
        if li[i][j] == "S":
            sy = i
            sx = j
        if li[i][j] == "1":
            gy = i
            gx = j
        elif li[i][j] == "2":
            num[1] = [i,j]
        elif li[i][j] == "3":
            num[2] = [i,j]
        elif li[i][j] == "4":
            num[3] = [i,j]
        elif li[i][j] == "5":
            num[4] = [i,j]
        elif li[i][j] == "6":
            num[5] = [i,j]
        elif li[i][j] == "7":
            num[6] = [i,j]
        elif li[i][j] == "8":
            num[7] = [i,j]
        elif li[i][j] == "9":
            num[8] = [i,j]
ans = bfs(sy,sx,gy,gx)
num[0] = [gy,gx]
for i in range(n-1):
    sy,sx = num[i]
    gy,gx = num[i+1]
    ans += bfs(sy,sx,gy,gx)
print(ans)