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 copy

(h, w, n) = list(map(int, input().split()))
dis = [[] for i in range(n + 1)]


def setArr(ph):
    global dis
    res = [False for i in range(w + 2)]
    for i, x in enumerate(list(input())):
        if x == "X":
            continue
        res[i + 1] = True
        if x == ".":
            continue
        if x == "S":
            dis[0] = [ph, i + 1]
            continue
        dis[int(x)] = [ph, i + 1]
    return res


arr = [[] for i in range(h + 2)]
arr[0] = [False for i in range(h + 2)]
arr[-1] = [False for i in range(h + 2)]
for i in range(1, h + 1):
    arr[i] = setArr(i)
res = 0
move = [[1, 0], [0, 1], [-1, 0], [0, -1]]


def ze(start, goal):
    arra = copy.deepcopy(arr)
    global res
    queue = [start, [-1, -1]]
    ap = queue.append
    zu = False
    for q in queue:
        if q[0] < 0:
            res += 1
            ap([-1, -1])
            continue
        if not arra[q[0]][q[1]]:
            continue
        for m in move:
            de = [q[0] + m[0], q[1] + m[1]]
            if de == goal:
                res += 1
                zu = True
                break
            if arra[de[0]][de[1]]:
                ap(de)
        if zu:
            break
        arra[q[0]][q[1]] = False


for i in range(n):
    ze(dis[i], dis[i + 1])

print(res)

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])]
    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:
                print(min_path[current[1]-1][current[0]])
                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

Python: import  copy
h = w = 0
mymap =[]
const_mymap = []
qlist = []
ans = 0
def bfs(n):
    while True:
        if len(qlist) != 0:
            temp = qlist.pop(0)
            x = temp[0]
            y = temp[1]
            deep = temp[2]

            #print(temp)
            if mymap[y][x] == str(n):
                #print('get')
                return temp
            if mymap[y][x] != '*':
                mymap[y] = mymap[y][:x] + '*' + mymap[y][x + 1:]

                if x + 1 < w:
                    if mymap[y][x + 1] not in '*X':
                        qlist.append([x + 1, y, deep + 1])
                if x - 1 >= 0:
                    if mymap[y][x - 1] not in '*X':
                        qlist.append([x - 1, y, deep + 1])
                if y + 1 < h:
                    if mymap[y + 1][x] not in '*X':
                        qlist.append([x, y + 1, deep + 1])
                if y - 1 >= 0:
                    if mymap[y - 1][x] not in '*X':
                        qlist.append([x, y - 1, deep + 1])
        else:
            break
h, w, n = list(map(lambda x: int(x), input().split(" ")))
for i in range(0, h):
    const_mymap.append(input())

mymap = copy.deepcopy(const_mymap)

for i in range(0, h):
    for j in range(0, w):
        if mymap[i][j] == 'S':
            nstart = [j, i, 0]
#print(nstart)

qlist.append(nstart)
#print(qlist)
for i in range (n):
    #print(i)
    mymap = copy.deepcopy(const_mymap)
    xy = bfs(i+1)
    #print(xy)
    #print(const_mymap)
    ans = xy[2]
    qlist = []
    qlist.append(xy)
    #print(ans)

print(ans)