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 collections import deque

H, W, N = map(int, input().split())
field = [list(input()) for i in range(H)]
node_posi = {}
Q = deque()

def search(start, goal):
	Q.append(start)
	while Q:
		x, y, c = Q.popleft()
		searched[y][x] = 1
		
		if ([x, y, 0] == goal):
			return c
		
		for q in range(4):
			nx = x + [1,0,-1,0][q]
			ny = y + [0,1,0,-1][q]
			if (nx >= 0 and nx <= W-1) and (ny >= 0 and ny <= H-1) and (searched[ny][nx] == 0) and (field[ny][nx] != 'X'):
				Q.append([nx, ny, c+1])

for i in range(H):
	for j in range(W):
		if field[i][j] in 'S123456789':
			node_posi[field[i][j]] = [j, i, 0]

s =	'S123456789'
cost = 0
for i in range(len(node_posi)-1):
	Q.clear()
	searched = [[0]*W for i in range(H)]
	cost += search(node_posi[s[i]], node_posi[s[i+1]])
print(cost)

Python: from queue import Queue
INF = 20000000
q = Queue()
dx = [-1, 0, 1, 0]
dy = [0, -1, 0, 1]
smp = [[INF for i in range(1002)] for j in range(1002)]
mp = [['X' for i in range(1002)] for j in range(1002)]
ipt = input().split('\n')
H, W, n = map(int,ipt[0].split())
for i in range(1, H+1):
    for j in range(1, W+1):
        mp[i][j] = ipt[i][j-1];
x = y = 0
for i in range(1, H+1):
    for j in range(1, W+1):
        if mp[i][j]=='S':
            x = j; y = i;
c = 0; ans = 0;
q.put([x,y]); smp[y][x] = 0;
while c<n:
    p = q.get()
    x = p[0]; y = p[1];
    if mp[y][x]==chr(ord('1')+c):
        ans += smp[y][x]; c+=1;
        if c==n: break;
        while q.empty()==False: q.get()
        for i in range(1, H+1):
            for j in range(1, W+1):
                smp[i][j] = INF
        smp[y][x] = 0
    for i in range(4):
        if mp[y+dy[i]][x+dx[i]]!='X' and smp[y+dy[i]][x+dx[i]]==INF:
            q.put([x+dx[i], y+dy[i]]);
            smp[y+dy[i]][x+dx[i]] = smp[y][x]+1;
print(ans)

Python: #import queue #queue
INF=1145141919
dx=[1,-1,0,0]
dy=[0,0,1,-1]
def search(cor_s,dst):
    mem=[[INF for i in range(a[1])]for j in range(a[0])]
    #q=queue.Queue() #queue
    #q.put(cor_s) #queue
    li=[cor_s] #list
    mem[cor_s[0]][cor_s[1]]=0
    #while not q.empty(): #queue
    while len(li)!=0: #list
        #cor=q.get() #queue
        cor=li.pop(0) #list
        for i in range(4):
            x=cor[0]+dx[i]
            y=cor[1]+dy[i]
            if 0<=x<a[0] and 0<=y<a[1] and s[x][y]!='X' and mem[x][y]==INF:
                mem[x][y]=mem[cor[0]][cor[1]]+1
                if s[x][y]==str(dst):return [[x,y],mem[x][y]]
                else:
                    #q.put([x,y]) #queue
                    li.append([x,y])
#
a=[int(num)for num in input().split(' ')]
s=[list(input()) for i in range(a[0])]
pos_s=[]
time=0
for li in s:
    if 'S' in li:pos_s=[s.index(li),li.index('S')]
for i in range(a[2]):
    ret_l=search(pos_s,i+1)
    pos_s=ret_l[0]
    time+=ret_l[1]
print(time)

Python: h,w,n = map(int, input().split())
stage = [input() for i in range(h)]
starts = [str(i) for i in range(n)]
goals = [str(i+1) for i in range(n)]
starts_y = [0 for i in range(n)]
starts_x = [0 for i in range(n)]
goals_y = [0 for i in range(n)]
goals_x = [0 for i in range(n)]

starts[0] = "S"
for y in range(h):
	for x in range(w):
		if stage[y][x] in starts:
			starts_y[starts.index(stage[y][x])] = y
			starts_x[starts.index(stage[y][x])] = x
		if stage[y][x] in goals:
			goals_y[goals.index(stage[y][x])] = y
			goals_x[goals.index(stage[y][x])] = x


sum = 0

for start_y, start_x, goal_y, goal_x in zip(starts_y, starts_x, goals_y, goals_x):
	bfs_map = [[-1 for j in range(w)] for i in range(h)]
	data_y = [start_y]
	data_x = [start_x]
	bfs_map[start_y][start_x] = 0
	goal = False
	
	while (data_y) and not goal:
		y = data_y.pop(0)
		x = data_x.pop(0)
		goal = False
	
		for i in range(4):
			ny = y + [0,1,0,-1][i]
			nx = x + [1,0,-1,0][i]
			
			if ny >= 0 and ny < h and nx >= 0 and nx < w:
				if bfs_map[ny][nx] == -1 and stage[ny][nx] != "X":
					bfs_map[ny][nx] = bfs_map[y][x]+1
					data_y.append(ny)
					data_x.append(nx)
			if bfs_map[goal_y][goal_x] != -1:
				sum += bfs_map[goal_y][goal_x]
				goal = True
				break

print(sum)

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,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]: # at the same cheese-power number
                    if field[ny][nx] == goal_N: # goal
                        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):

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