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 v():
 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)
if'__main__'==__name__:v()

Python: from collections import deque

def main():
  h, w, n = map(int, input().split())
  mp = ["X" + input() + "X" for _ in range(h)]
  mp.insert(0, "X" * (w + 2))
  mp.append("X" * (w + 2))
  
  poss = [None] * (n + 1)
  for y in range(1, h + 1):
    for x in range(1, w + 1):
      if mp[y][x] == "S":
        poss[0] = (x, y)
      elif "1" <= mp[y][x] <= "9":
        poss[int(mp[y][x])] = (x, y)
  
  ans = 0
  vec = ((1, 0), (0, -1), (-1, 0), (0, 1))
  for i in range(n):
    sx, sy = poss[i]
    gx, gy = poss[i + 1]
    used = [[False] * (w + 2) for _ in range(h + 2)]
    used[sy][sx] = True
    que = deque()
    push = que.append
    pop = que.popleft
    push((0, sx, sy))
    while que:
      cnt, x, y = pop()
      if (x, y) == (gx, gy):
        ans += cnt
        break
      
      for dx, dy in vec:
        nx, ny = x + dx, y + dy
        if used[ny][nx] or mp[ny][nx] == "X":continue
        used[ny][nx] = True
        push((cnt + 1, nx, ny))
  
  print(ans)

main()

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,k+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: # -*- 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)):
		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: 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()