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: 
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().rstrip().split()
    for i in range(len(row)):
        try:
            row[i] = int(row[i])
        except:
            continue
    field.append(row)
    if len(field) == int(field[0][0]) + 1:
        main(field)
        break

Python: # -*- coding: utf-8 -*-

import sys
sys.setrecursionlimit(10**7)

def search(field,distance,ch,cv,eh,ev,step):
	if not (0<=ch<len(field)):		return
	if not (0<=cv<len(field[ch])):	return
	if field[ch][cv]=='X':			return
	if distance[ch][cv]<step: 		return

	distance[ch][cv] = step
	search(field,distance,ch+1,cv,eh,ev,step+1)
	search(field,distance,ch-1,cv,eh,ev,step+1)
	search(field,distance,ch,cv+1,eh,ev,step+1)
	search(field,distance,ch,cv-1,eh,ev,step+1)

def calculate_distance(field,locations,current_HP):
	ch,cv=locations[current_HP-1]
	eh,ev=locations[current_HP]
	distance=[[10**6 for _ in range(len(field[0]))] for __ in range(len(field))]
	search(field,distance,ch,cv,eh,ev,0)
#	print('='*50)
#	for v in distance:
#		print(v)
#	print('-'*50)
	return distance[eh][ev]
#	return 0

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


class HW(object):
    def __init__(self, args: tuple):
        self.h = args[0]
        self.w = args[1]


h, w, n = map(int, input().split())
maze = [input() for i in range(h)]

start = HW((0, 0))
now = HW((0, 0))
nxt = HW((0, 0))

cnt = 0
visited = []


def bfs(target: int) -> int:
    global visited, start, h, w
    visited = [[-1 for _ in range(w)] for _ in range(h)]
    q = queue.Queue()
    q.put((start.h, start.w))
    visited[start.h][start.w] = 0

    while not q.empty():
        tmp = q.get()
        now.h, now.w = tmp[0], tmp[1]
        if maze[now.h][now.w] == str(target):
            start = now
            return visited[now.h][now.w]

        for k in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            nxt.h, nxt.w = now.h + k[0], now.w + k[1]
            if not 0 <= nxt.h < h or not 0 <= nxt.w < w:
                continue
            elif maze[nxt.h][nxt.w] == "X":
                continue
            elif visited[nxt.h][nxt.w] == -1:
                q.put((nxt.h, nxt.w))
                visited[nxt.h][nxt.w] = visited[now.h][now.w] + 1


def main() -> None:
    for j in range(h):
        for i in range(w):
            if maze[j][i] == "S":
                start.h, start.w = j, i

    for i in range(n):
        global cnt
        cnt += bfs(i + 1)
    print(cnt)


if __name__ == "__main__":
    main()

Python: H, W, N = map(int, input().split())
field = [list(input()) for i in range(H)]
node_posi = {}
Q = []

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)]
	start, goal = node_posi[s[i]], node_posi[s[i+1]]
	Q.append(start)
	while Q:
		x, y, c = Q.pop(0)
		searched[y][x] = 1
		
		if ([x, y, 0] == goal):
			cost += c
			break
		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])
print(cost)

Python: from collections import deque
H,W,N=map(int,input().split())
e='X'*(W+2)
M=e+''.join('X'+input()+'X'for _ in[0]*H)+e
m=(1,-1,W+2,-W-2)
def f(s,g):
 p,t=s,0
 q=deque()
 b=[1]*len(M);b[s]=0
 while 1:
  for d in m:
   n=p+d
   if'X'!=M[n]and b[n]:
    if M[n]==g:return(n,t+1)
    b[n]=0;q.append([n,t+1])
  p,t=q.popleft()
s=M.find('S')
a=0
for i in range(1,N+1):
 s,t=f(s,str(i))
 a+=t
print(a)

Python: from collections import deque
H,W,N = map(int,input().split())
graph = []
S = None
for i in range(H):
  row = list(input())
  if "S" in row:
    s = row.index("S")
    S = (i,s)
  graph.append(row)

def bfs(S, target):
  q = deque([S])
  visited = set()
  step = 0

  while q:
    l = len(q)
    next_q = deque()

    for _ in range(l):
      r,c = q.popleft()
      if graph[r][c] == str(target):
        return step, r, c
      visited.add((r,c))

      for x,y in [(1,0), (0,1), (-1,0), (0,-1)]:
        nr,nc = r+x,c+y
        if nr<0 or nc<0 or nr>=H or nc>=W: continue
        if (nr,nc) in visited: continue
        if (nr,nc) in next_q: continue
        if graph[nr][nc] == target:
          return step+1, nr, nc
        if graph[nr][nc] != "X":
          next_q.append((nr,nc))

    step += 1
    q = next_q

res = 0
for i in range(1, N+1):
  steps, x,y = bfs(S, i)
  S = (x,y)
  res += steps
  # print(i, steps, (x,y))

print(res)