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: moves = [(0, -1), (0, 1), (-1, 0), (1, 0)]
 
 
def search(dataset):
    min_time = 0
    mouse = 1
    gx, gy = get_start(dataset)
    for i in xrange(N):
        gx, gy, min_time_tmp = bfs(dataset, (gx, gy), mouse)
        mouse += 1
        min_time += min_time_tmp
    print(min_time)
 
 
def bfs(dataset, start, mouse):
    INF = 10000000
    min_time = [[INF for j in range(W)] for i in range(H)]
    min_time[start[0]][start[1]] = 0
    queue = [start]
 
    while len(queue) != 0:
        dx, dy = queue.pop(0)
        for i, j in moves:
            nx = dx + i
            ny = dy + j
            if 0 <= nx < H and 0 <= ny < W and dataset[nx][ny] != 'X' and min_time[nx][ny] == INF:
                cell = dataset[nx][ny]
            else:
                continue
            if type(cell) is int:
                if mouse == int(cell):
                    min_time[nx][ny] = min_time[dx][dy] + 1
                    return nx, ny, min_time[nx][ny]
            min_time[nx][ny] = min_time[dx][dy] + 1
            queue.append((nx, ny))
 
 
def get_start(dataset):
    for i in range(H):
        rows = dataset[i]
        for j in range(W):
            cell = rows[j]
            if cell == 'S':
                return i, j
 
 
dataset = []
while True:
    line = input().rstrip().split()
    if len(line) == 3:
        H, W, N = map(int, line)
    else:
        row = []
        for e in line[0]:
            if e.isdigit():
                row.append(int(e))
            else:
                row.append(e)
        dataset.append(row)
    if len(dataset) == H:
        search(dataset)
        break

Python: h,w,n = map(int, input().split())
stage = [input() for i in range(h)]
map(lambda x: x if x != 'S' else 0, stage)
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[int(stage[y][x])] = y
			starts_x[int(stage[y][x])] = x
		if stage[y][x] in goals:
			goals_y[int(stage[y][x])-1] = y
			goals_x[int(stage[y][x])-1] = 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: import sys
sys.setrecursionlimit(100000000)


def getStart(field):
    search_field = field[1:]     # cut the first [H,W,N] for min_path matrix
    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)
        print("pop",current)
        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]: # at the same cheese-power number
                    if field[ny][nx] == goal_N: # goal
                        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):

    # field = [[10,10,9],
    # [".","X",".",".",".","X",".","S",".","X"],
    # [6,".",".",5,"X",".",".","X",1,"X"],
    # [".",".",".","X","X","X","X",".",".","X"],
    # ["X",".",".",9,"X",".",".",".","X","."],
    # [8,".","X",2,"X",".",".","X",3,"X"],
    # [".",".",".","X","X",".","X",4,".","."],
    # ["X","X",".",".",".",".",7,"X",".","."],
    # ["X",".",".","X",".",".","X","X",".","."],
    # ["X",".",".",".","X",".","X","X",".","."],
    # [".",".","X",".",".",".",".",".",".","."]]

    sx,sy = getStart(field)
    bfs(field,sx,sy,field[0][2])

matrix = []
while True:
    row = input().split()
    if len(row) == 1:
        re_row = []
        for char in row[0]:
            if char.isdigit():
                re_row.append(int(char))
            else:
                re_row.append(char)
        matrix.append(re_row)
    else:
        matrix.append(row)
    if len(matrix) == int(matrix[0][0]) + 1:
        main()
        break

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
    goal_lot
    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()