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 time, sys#
from collections import deque

H, W, N = map(int, input().split())
field = [list(input()) for i in range(H)]
'''
20 30 9
.......X..8.XXXX.XX..XX.X.XX..
X.XX....X.XX..X.X.X....XXXX..X
..X.X..XX..X.....XX.X..X.XX...
....X.X.X.XXX.X..X..X.X..XX.X.
..XXX.XX...X.X....X.X..X..X...
..X...........X.X...X.1.XX...X
.X.X....X..XX..XX......9.X...4
..X....X........X......X......
....XXX.X...XX.X.....X.X..X.X.
..S..XXX..X....X.X.......X..X.
.5...XX..X.X..X....X...XXX....
..X...X.X....X....X..X.2X.....
XXXXXXXX.X.XX..XX..XX.......X.
.....X...........3..XX.XXX.X.X
..X.....X..X..XX.XX..X.X...XX.
...X..X.XXX.XX......X...X..XXX
.X.XX.X.........X.X...X...X..X
..X...X..X..XX..XXX..X.XX...X.
X....X.X....X...X.X..XX.XX..X.
...X6X..X........X.X.....7.X..
'''

#input = input().split('\n')#
#H, W, N = map(int, input.pop(0).split())#
#field = [line for line in input]#
node_posi = [0 for i in range(N+1)]

#s1 = time.time()#
nodes = 'S123456789'
for i in range(H):
	for j in range(W):
		if field[i][j] in nodes:
			node_posi[nodes.index(field[i][j])] = [j, i]
#e1 = time.time()#
#print("b:{}".format(e1-s1))#

cost = 0
#count = 1#
for i in range(len(node_posi)-1):
	#s2 = time.time()#
	searched = [[-1]*W for i in range(H)]
	start, goal = node_posi[i], node_posi[i+1]
	Q = deque([start])
	searched[start[1]][start[0]] = 0
	goal_flag = False
	
	while Q and not goal_flag:
		x, y = Q.popleft()
		goal_flag = False

		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 and ny >= 0 and ny < H:
				if searched[ny][nx] == -1 and field[ny][nx] != 'X':
					Q.append([nx, ny])
					searched[ny][nx] = searched[y][x] + 1
					if ([nx, ny] == goal):
						cost += searched[ny][nx]
						goal_flag = True
						break

			#s = "\n".join(["".join(map(lambda x: str(x)[:1], j)) for j in searched])#
			#sys.stdout.write("\r{}".format(s))#
			#sys.stdout.flush()#
	
	#e2 = time.time()#
	#print("{}:{}".format(count, e2-s2))#
	#count += 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:
            int(row[i])
        except:
            continue
    field.append(row)
    if len(field) == int(field[0][0]) + 1:
        main(field)
        break

Python: from copy import deepcopy
from collections import deque

H, W, N = map(int, input().split())
town = [list(input()) for i in range(H)]

move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
queue = deque()
stamina = 1
town_tmp = deepcopy(town)

for i in range(H):
    for j in range(W):
        if town[i][j] == 'S':
            queue.append((i, j, 0))
            town_tmp[i][j] = 'X'

while True:
    i, j, time = queue.popleft()
    for di, dj in move:
        ni, nj = i + di, j + dj
        if 0 <= ni < H and 0 <= nj < W:
            if town_tmp[ni][nj] == str(stamina):
                stamina += 1
                if stamina == N + 1:
                    print(time+1)
                    exit()
                town_tmp = deepcopy(town)
                queue = deque()
                queue.append((ni, nj, time+1))
                break
            elif town_tmp[ni][nj] == 'X':
                continue
            else:
                queue.append((ni, nj, time+1))
                town_tmp[ni][nj] = 'X'

Python: import collections


def search(sy, sx, gy, gx):
    visited = [[False for j in range(W)] for i in range(H)]
    visited[sy][sx] = True

    dq = collections.deque()
    dq.append((0, sy, sx))
    while dq:
        cost, y, x = dq.popleft()
        if (y, x) == (gy, gx):
            return cost
        for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):
            ny = y + dy
            nx = x + dx
            if ny < 0 or ny >= H or nx < 0 or nx >= W:
                continue
            if visited[ny][nx] or cells[ny][nx] == 'X':
                continue
            dq.append((cost + 1, ny, nx))
            visited[ny][nx] = True


def main(H, W, N, cells):
    points = {}
    for i in range(H):
        for j in range(W):
            points[cells[i][j]] = (i, j)
    points['0'] = points['S']
    total = 0
    for i in range(1, N + 1):
        sy, sx = points[str(i - 1)]
        gy, gx = points[str(i)]
        total += search(sy, sx, gy, gx)
    print(total)


if __name__ == '__main__':
    H, W, N = map(int, input().split())

    cells = []
    for i in range(H):
        cells.append(input())
    main(H, W, N, cells)