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 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0558

"""
import sys
from sys import stdin
from collections import deque
input = stdin.readline


def bfs(field, sx, sy, gx, gy):
    # ????????????????§????????????´????????§?¨??????????
    dy = [-1, 1, 0, 0]
    dx = [0, 0, -1, 1]

    # ??°???????????????(?§????????????£????????????????????????????????§??????????????¨)
    Y = len(field)
    X = len(field[0])
    d = [[float('inf')] * X for _ in range(Y)] #  ??????????????°?????????????????¢???INF??§?????????

    # ??°???????????????(?§????????????£????????????????????????????????§??????????????¨)
    Y = len(field)
    X = len(field[0])

    Q = deque()
    Q.append((sx, sy))
    d[sy][sx] = 0               #  ??????????????°??????????????????0
    while Q:
        cx, cy = Q.popleft()        #  ?????¨??°?????§?¨?
        if cx == gx and cy == gy:
            break
        for i in range(4):
            nx = cx + dx[i]
            ny = cy + dy[i]
            # ?§?????????? ??°????????????????????????????????? and ?£?????????£???????????? and ??¢?????¢?´¢?????§?????? ??´???
            if (0 <= nx < X) and (0 <= ny < Y) and field[ny][nx] != 'X' and d[ny][nx] == float('inf'):
                Q.append((nx, ny))
                d[ny][nx] = d[cy][cx] + 1
    return d[gy][gx]


def find_mark(data):
    founds = []
    if 'S' in data:
        founds.append(['S', data.index('S')])
    if '1' in data:
        founds.append(['1', data.index('1')])
    if '2' in data:
        founds.append(['2', data.index('2')])
    if '3' in data:
        founds.append(['3', data.index('3')])
    if '4' in data:
        founds.append(['4', data.index('4')])
    if '5' in data:
        founds.append(['5', data.index('5')])
    if '6' in data:
        founds.append(['6', data.index('6')])
    if '7' in data:
        founds.append(['7', data.index('7')])
    if '8' in data:
        founds.append(['8', data.index('8')])
    if '9' in data:
        founds.append(['9', data.index('9')])
    return founds

def solve(field, N):
    # ??????????????°???(S)??¨??´????????°???(G)?????????
    pos = [[None, None] for _ in range(N+1)]
    for y, row in enumerate(field):
        res = find_mark(row)
        for mark, x in res:
            if mark is not None:
                if mark == 'S':
                    pos[0] = [x, y]
                else:
                    pos[int(mark)] = [x, y]

    total_move = 0
    start = pos[0]
    for goal in pos[1:]:
        sx, sy = start
        gx, gy = goal
        res = bfs(field, sx, sy, gx, gy)
        # print('From: ({}, {}) -> To: ({}, {}), step: {}'.format(sx, sy, gx, gy, res))
        # print('min move: {}'.format(abs(sx-gx) + abs(sy-gy)))
        total_move += res
        start = goal

    return total_move


def main(args):
    # N = 9
    # data = [
    #     '.X...X.S.X',
    #     '6..5X..X1X',
    #     '...XXXX..X',
    #     'X..9X...X.',
    #     '8.X2X..X3X',
    #     '...XX.X4..',
    #     'XX....7X..',
    #     'X..X..XX..',
    #     'X...X.XX..',
    #     '..X.......'
    # ]
    H, W, N = map(int, input().split())
    data = [input().strip('\n') for _ in range(H)]
    field = [list(x) for x in data] #  data????????????????????????????????????????????????
    result = solve(field, N)
    print(result)


if __name__ == '__main__':
    main(sys.argv[1:])

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

import sys
sys.setrecursionlimit(10**6)

def calculate_distance(field,locations,current_HP):
	sx,sy = locations[current_HP-1]
	ex,ey = locations[current_HP]

	is_visit = [[False for _ in range(len(field[0]))] for __ in range(len(field))]
	is_visit[sx][sy]=True

	frontier = set()
	frontier.add(locations[current_HP-1])
	step = 0
	while not is_visit[ex][ey]:
		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
				is_visit[nx][ny] = True
				next_frontier.add((nx,ny))
		if len(next_frontier)==0: return
		frontier = next_frontier
		step += 1
	return step


def solve(field,locations):
	total_step=0
	for current_HP in range(1,len(locations)):
		print('current HP',current_HP)
		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()