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

move_y = [1,-1,0,0]
move_x = [0,0,1,-1]
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 len(data_y) != 0 and not goal:
		y = data_y.pop(0)
		x = data_x.pop(0)
		goal = False
	
		for i in range(4):
			y += move_y[i]
			x += move_x[i]
			
			if y >= 0 and y < h and x >= 0 and x < w:
				if bfs_map[y][x] == -1 and stage[y][x] != "x":
					bfs_map[y][x] = bfs_map[y-move_y[i]][x-move_x[i]]+1
					data_y.append(y)
					data_x.append(x)
				if bfs_map[goal_y][goal_x] != -1:
					sum += bfs_map[goal_y][goal_x]
					goal = True
					break

			y -= move_y[i]
			x -= move_x[i]
			
print(sum)

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??§?????????
    Q = deque()
    Q.append((sx, sy))
    d[sy][sx] = 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 solve(field, N):
    # ??°???????????????(?§????????????£????????????????????????????????§??????????????¨)
    Y = len(field)
    X = len(field[0])

    # ??????????????°???(S)??¨??´????????°???(G)?????????
    sx = None                   #  ??????????????°????????§?¨?
    sy = None


    start_mark = 'S'
    for y in range(Y):
        for x in range(X):
            if field[y][x] == start_mark:
                sx = x
                sy = y
                break
        if sx != None:
            break

    total_move = 0
    for i in range(1, N+1):
        gx = None                   #  ??´????????°????????§?¨?
        gy = None
        goal_mark = str(i)

        for y in range(Y):
            for x in range(X):
                if field[y][x] == goal_mark:
                    gx = x
                    gy = y
                    break
            if gx != None:
                break
        res = bfs(field, sx, sy, gx, gy)
        total_move += res
        sx = gx
        sy = gy

    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() 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: import copy
import queue
def bfs(count, x, y, cheese):
    q = queue.Queue()
    q.put((count,x,y))
    tempVisited = copy.deepcopy(visited)
    tempVisited[x][y] = True
    
    while q.qsize()>0:
        tempc,tempx,tempy = q.get(0)
        if geo[tempx][tempy] == cheese:
            return tempc,tempx,tempy
        for i in range(4):
            neox = tempx+dx[i]
            neoy = tempy+dy[i]
            if canGoTo(neox,neoy, tempVisited):
                #if (tempc+1,neox,neoy) not in q:
                q.put((tempc+1,neox,neoy))
                tempVisited[neox][neoy]=True
    return (-1,-1,-1)

def canGoTo(x,y,tempVisited):
    if 0<=x<H and 0<=y<W:
        return not tempVisited[x][y]
    return False

dx = [0,1,0,-1]
dy = [-1,0,1,0]

data = input().split(' ')
H,W,N = map(int, data)

#maps
geo = [[None for i in range(W)] for j in range(H)]
visited = [[False for i in range(W)] for j in range(H)]

x,y=-1,-1
for i in range(H):
    line = input()
    for j in range(W):
        p = line[j:j+1]
        geo[i][j] = p
        if p == 'X':
            visited[i][j] = True
        elif p == 'S':
            x,y, = i,j
            
count = 0
for n in range(1,N+1):
    count,x,y = bfs(count,x,y,str(n))
print(count)