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: # -*- coding: utf-8 -*-

import sys
sys.setrecursionlimit(10**6)

def calculate_distance(field,locations,current_HP):
	is_visit = [[False for _ in range(len(field[0]))] for __ in range(len(field))]
	frontier = set()
	frontier.add(locations[current_HP-1])
	for step in range(10**4):
		for cx,cy in frontier:
			if (cx,cy)==locations[current_HP]: return step+1
			is_visit[cx][cy]=True
		next_frontier = set()
		for cx,cy in list(frontier):
			for dx,dy in [[0,1],[0,-1],[1,0],[-1,0]]:
				nx = cx+dx
				ny = cy+dy
				if not (0<=nx<len(field)):		continue
				if not (0<=ny<len(field[nx])):	continue
				if field[nx][ny]=='X':			continue
				if is_visit[nx][ny]: 			continue
				next_frontier.add((nx,ny))
		if len(next_frontier)==0: return
		frontier = next_frontier
	return -10*3

def solve(field,locations):
	total_step=0
	for current_HP in range(1,len(locations)):
		total_step += calculate_distance(field,locations,current_HP)
	return total_step

def main():
	line=input().strip()
	H,W,N=list(map(int,line.split(' ')))
	field,locations=list(),dict()
	for i in range(H):
		field.append(list(input().strip()))
		for j,x in enumerate(field[-1]):
			if x=='S':
				locations[0] = (i,j,)
			if x.isdigit():
				x = int(x)
				field[-1][j] = x
				locations[x] = (i,j,)
	print(solve(field,locations))

if __name__=='__main__':
	main()

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

field = []
while True:
    row = input().split()
    for i in range(len(row)):
        try:
            row[i] = int(row[i])
        except:
            continue
    field.append(row)
    if len(field) == field[0][0] + 1:
        main(field)
        break

Python: from collections import deque

h,w,n=map(int,input().split())

w+=2
G=[list('X'*w)]
for i in range(h):
    G+=[list('X'+input()+'X')]
G+=[list('X'*w)]
h+=2

def bfs(sx,sy,gx,gy):
    que=deque()
    g=[[float('inf')]*w for _ in range(h)]
    g[sx][sy]=0
    que.append((sx,sy))
    xy=[(0,-1),(-1,0),(1,0),(0,1)]

    while que:
        x,y=que.popleft()
        if x==gx and y==gy:break
        for dx,dy in xy:
            nx=x+dx
            ny=y+dy
            if G[nx][ny]!='X' and g[nx][ny]==float('inf'):
                que.append((nx,ny))
                g[nx][ny]=g[x][y]+1
    return g[gx][gy]


res=0

goals=[(0,0) for i in range(n+1)]

for i in range(1,h):
    for j in range(1,w):
        if G[i][j]=='S':
            goals[0]=(i,j)
        if G[i][j].isdecimal():
            num=int(G[i][j])
            goals[num]=(i,j)

for i in range(len(goals)-1):
    sx,sy=goals[i][0],goals[i][1]
    gx,gy=goals[i+1][0],goals[i+1][1]
    
    res+=bfs(sx,sy,gx,gy)

print(res)