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 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)]
H, W, n = map(int,raw_input().split())
for i in range(1, H+1):
    ipt = raw_input()
    for j in range(1, W+1):
        mp[i][j] = ipt[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: def bfs(field,H,W,start_x,start_y,tmp_N):
    direction = [[-1,0],[1,0],[0,-1],[0,1]]
    que = []
    que.append([start_x,start_y])
    INF = 1000000
    min_path = [[INF] * W for i in range(H)]
    min_path[start_y][start_x] = 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 < W and 0 <= ny < H and field[ny][nx] != "X" and min_path[ny][nx] == INF:
                min_path[ny][nx] = min_path[current[1]][current[0]] + 1
                if field[ny][nx] == tmp_N:
                    return nx,ny,min_path[ny][nx]
                else:
                    que.append([nx,ny])

def getField():
    matrix = []
    first = input().strip()
    H,W,N = map(int,first.split())
    for i in range(H):
        row = list(input().strip())
        for j in range(W):
            if row[j].isdigit():
                row[j] = int(row[j])
        matrix.append(row)
    return matrix,H,W,N

def getStart(field):
    for y in range(len(field)):
        for x in range(len(field[0])):
            if field[y][x] == "S":
                return x,y

def main():
    matrix,H,W,N = getField()
    sx,sy = getStart(matrix)
    distance = 0
    tmp_x,tmp_y,tmp_dist = bfs(matrix,H,W,sx,sy,1)
    distance += tmp_dist
    tmps = [tmp_x,tmp_y]
    for k in range(N-1):
        tmp_x,tmp_y,tmp_dist = bfs(matrix,H,W,tmps[0],tmps[1],k+2)
        distance += tmp_dist
        tmps = [tmp_x,tmp_y]
    print(distance)

if __name__=='__main__':
    main()

Python: #!/usr/bin/env python
# -*- coding: utf-8 -*-

import heapq
import sys

def check_out_of_map(pos,H,W):
    if pos[0] < 0 or pos[1] < 0:
        return False
    if pos[0] >= H or pos[1] >= W:
        return False
    return True

def bfs(s,g,Map,H,W):
    queue = []
    queue.append(s)
    dist = [[-1 for i in range(W)] for j in range(H)]
    direct = [(1,0),(-1,0),(0,1),(0,-1)]
    count = 0
    dist[s[0]][s[1]] = 0

    while queue != []:
        q = queue.pop(0)
        if q == g:
            return dist[q[0]][q[1]]
        for i in range(4):
            nextPos = (q[0]+direct[i][0],q[1]+direct[i][1])
            if check_out_of_map(nextPos,H,W) and Map[nextPos[0]][nextPos[1]] != "X":
                if dist[nextPos[0]][nextPos[1]] == -1:
                    dist[nextPos[0]][nextPos[1]] = dist[q[0]][q[1]] + 1
                    queue.append(nextPos)

H,W,N = map(int,input().split(" "))
cheese_queue = []
Map = []
for i in range(H):
    count = 0
    line = []
    while True:
        char = sys.stdin.read(1)
        if char == "S":
            s = (i,count)
        elif char.isnumeric():
            heapq.heappush(cheese_queue,(int(char),(i,count)))
        elif char == "\n":
            break
        line.append(char)
        count += 1
    Map.append(line)
count = 0
while cheese_queue != []:
    q = heapq.heappop(cheese_queue)
    count += bfs(s,q[1],Map,H,W)
    s = q[1]
print(count)

Python: import sys

file_input = sys.stdin

H, W, N = map(int, file_input.readline().split())

town_map = 'X' * (W + 2)
for line in file_input:
    town_map += 'X' + line.rstrip() + 'X'
town_map += 'X' * (W + 2)

move = (1, -1, W + 2, -W - 2)

from collections import deque

def search(start_pos, goal_lot):
    mouse = [start_pos, 0] # [position, elapsed time]
    q = deque()
    unvisited = [True] * len(town_map)
    unvisited[start_pos] = False
    while True:
        cur_pos = mouse[0]
        for d in move:
            next_pos = cur_pos + d
            lot = town_map[next_pos]
            if lot != 'X' and unvisited[next_pos]:
                if lot == goal_lot:
                    return (next_pos, mouse[1] + 1)
                else:
                    m = [next_pos, mouse[1] + 1]
                    unvisited[next_pos] = False
                    q.append(m)
        mouse = q.popleft()

def solve():
    start_pos = town_map.find('S')
    time = 0
    for i in range(1, N + 1):
        start_pos, t = search(start_pos, str(i))
        time += t
    print(time)

solve()

Python: import queue
h,w,n = map(int,input().split())
factrys = [None] * (n + 1)
ss = ["X" * (w + 2)]
for i in range(h):
  s = "X" + input() + "X"
  if "S" in s:
    factrys[0] = (i + 1,s.index("S"))
  for j in range(1,n + 1):
    if str(j) in s:
      factrys[j] = (i + 1,s.index(str(j)))
  ss.append(s)
ss.append("X" * (w + 2))
mp = []
que = queue.Queue()
def bfs(i):
  (x,y) = que.get()
#  print(i,x,y)
#  print(mp[x][y])
  if (x,y) == factrys[i + 1]:
    return mp[x][y]
  count = mp[x][y]
  if ss[x + 1][y] != "X" and mp[x + 1][y] == None:
    mp[x + 1][y] = count + 1
    que.put((x + 1, y))
  if ss[x - 1][y] != "X" and mp[x - 1][y] == None:
    mp[x - 1][y] = count + 1
    que.put((x - 1, y))
  if ss[x][y + 1] != "X" and mp[x][y + 1] == None:
    mp[x][y + 1] = count + 1
    que.put((x, y + 1))
  if ss[x][y - 1] != "X" and mp[x][y - 1] == None:
    mp[x][y - 1] = count + 1
    que.put((x, y - 1))
  return bfs(i)
ans = 0
for i in range(n):
  mp = [[None] * (w + 2) for j in range(h + 2)]
  x,y = factrys[i]
  mp[x][y] = 0
  que = queue.Queue()
  que.put((x,y))
  ans += (bfs(i))
print(ans)