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

file_input = sys.stdin

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

town_map = file_input.read()

start_index = town_map.index('S')

mouse = [start_index, 0, [start_index]]
# position, elapsed time, visited lot

from collections import deque

for goal in range(1, N + 1):
    q = deque()
    goal = str(goal)
    while True:
        cur_pos = mouse[0]
        
        ew_pos = cur_pos % (W + 1)
        if ew_pos < (W - 1):
            next_pos = cur_pos + 1
            lot = town_map[next_pos]
            if lot != 'X' and next_pos not in mouse[2]:
                if lot == goal:
                    mouse = [next_pos, mouse[1] + 1, [next_pos]]
                    break
                else:
                    m = [next_pos, mouse[1] + 1, mouse[2] + [next_pos]]
                    q.append(m)
        if ew_pos > 0:
            next_pos = cur_pos - 1
            lot = town_map[next_pos]
            if lot != 'X' and next_pos not in mouse[2]:
                if lot == goal:
                    mouse = [next_pos, mouse[1] + 1, [next_pos]]
                    break
                else:
                    m = [next_pos, mouse[1] + 1, mouse[2] + [next_pos]]
                    q.append(m)
        
        ns_pos = cur_pos // (W + 1)
        if ns_pos < (H - 1):
            next_pos = cur_pos + W + 1
            lot = town_map[next_pos]
            if lot != 'X' and next_pos not in mouse[2]:
                if lot == goal:
                    mouse = [next_pos, mouse[1] + 1, [next_pos]]
                    break
                else:
                    m = [next_pos, mouse[1] + 1, mouse[2] + [next_pos]]
                    q.append(m)
        if ns_pos > 0:
            next_pos = cur_pos - W - 1
            lot = town_map[next_pos]
            if lot != 'X' and next_pos not in mouse[2]:
                if lot == goal:
                    mouse = [next_pos, mouse[1] + 1, [next_pos]]
                    break
                else:
                    m = [next_pos, mouse[1] + 1, mouse[2] + [next_pos]]
                    q.append(m)
        mouse = q.popleft()

print(mouse[1])

Python: # field = [[3,3,1],["S",".","."],[".",".","."],[".",".",1]]

field = [[4,5,2],[".","X",".",".",1],[".",".",".",".","X"],[".","X","X",".","S"],[".",2,".","X","."]]

for i in range(len(field) - 1):
    for j in range(len(field[1])):
        if field[i+1][j] == "S":
            start_x = j
            start_y = i + 1
            break
# print(start_x,start_y)

def proceed(field,start_x,start_y,start_n,start_N,goal_N):
    # print("start[x]",start_x)
    # print("start[y]",start_y)
    x = [-1,0,1,0]
    y = [0,-1,0,1]
    next_x = []
    next_y = []
    next_N  = []
    # print("s_parameters",start_x,start_y,start_N,start_n,goal_N)

    for s_x,s_y,s_N in zip(start_x,start_y,start_N):
        for p_x,p_y in zip(x,y):
            if 1 <= s_y + p_y < len(field):
                #print("y",s_y + p_y)
                if 0 <= s_x + p_x < len(field[1]):
                    #print("x",s_x + p_x)
                    if field[s_y + p_y][s_x + p_x] != "X":
                        # print("x",s_x + p_x)
                        # print("y",s_y + p_y)
                        next_x.append(s_x + p_x)
                        next_y.append(s_y + p_y)
                        # print("[x]",next_x)
                        # print("[y]",next_y)
                        if field[s_y + p_y][s_x + p_x] == goal_N:
                            # print("GOAL_STATE",s_N)
                            next_N.append(s_N)
                            if s_N == goal_N:
                                # print("check",s_N,goal_N,start_N)
                                print(start_n + 1)
                                return  ## return None except 1
                        elif field[s_y + p_y][s_x + p_x] == s_N:
                                next_N.append(s_N + 1)
                                # print("EAT CHEESE",next_N)
                        else:
                            next_N.append(s_N)
    # print("next_N",next_N)
    next_n = start_n + 1
    proceed(field,next_x,next_y,next_n,next_N,goal_N)

proceed(field,[start_x],[start_y],0,[1],field[0][2])

Python: import sys
import copy
from collections import defaultdict

nesw = [[0, 1], [0, -1], [1, 0], [-1, 0]]
height, width, factory = map(int, input().split(" "))
root = []
start_y, start_x = -1, -1
targets = defaultdict(int)
for h in range(height):
    temp = [n for n in input()]
    if start_y == -1:
        try:
            start_y, start_x = h, temp.index("S")
        except:
            pass
    for i in range(1, factory + 1):
        if not targets[i]:
            try:
                targets[i] = (h, temp.index(str(i)))
            except:
                pass
    root.append(temp)
targets[0] = (start_y, start_x)
fastest_root = {}

# print(targets)

for start in range(factory):
    h, w = targets[start]
    end = start + 1
    end_y, end_x = targets[end]
    used = [[0 for n in range(width)] for m in range(height)]
    queue = [(h, w)]
    used[h][w] = 1
    flag = 0
    turn = 0
    while True:
        new_queue = []
        for q in queue:
            h, w = q
            for t in nesw:
                new_h, new_w = h + t[0], w + t[1]
                if 0 <= new_h < height and 0 <= new_w < width:
                    if new_h == end_y and new_w == end_x:
                        fastest_root[start] = {end:turn + 1}
                        flag = 1
                        break
                    elif not used[new_h][new_w] and root[new_h][new_w] != "X":
                        used[new_h][new_w] = 1
                        new_queue.append((new_h, new_w))
        if flag:
            break
        queue = new_queue
        turn += 1

perm = [n for n in range(0, factory + 1)]
answer = 0
for i in range(factory):
    answer += fastest_root[perm[i]][perm[i + 1]]

print(answer)