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 queue
from collections import deque
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))

def bfs(i):
  mp = [[None] * (w + 2) for j in range(h + 2)]
  x,y = factrys[i]
  mp[x][y] = 0
  que = deque()
  que.append((x, y))
  while True:
    (x,y) = que.popleft()
  #  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] is None:
      mp[x + 1][y] = count + 1
      que.append((x + 1, y))
    if ss[x - 1][y] != "X" and mp[x - 1][y] is None:
      mp[x - 1][y] = count + 1
      que.append((x - 1, y))
    if ss[x][y + 1] != "X" and mp[x][y + 1] is None:
      mp[x][y + 1] = count + 1
      que.append((x, y + 1))
    if ss[x][y - 1] != "X" and mp[x][y - 1] is None:
      mp[x][y - 1] = count + 1
      que.append((x, y - 1))

ans = 0
for i in range(n):
  ret = bfs(i)
  if ret is None:
    ans += 0
  else:
    ans += (ret)
print(ans)

Python: H, W, N = map(int, input().split())
graph = [list(input()) for _ in range(H)]
from collections import deque


def bfs_gird(start, x_lim=H, y_lim=W):
    seen = {start}
    todo = deque()
    todo.append(start)
    dis = {start: 0}

    one_steps = ((1, 0), (-1, 0), (0, 1), (0, -1))
    while todo:
        x, y, level = todo.popleft()
        for dx, dy in one_steps:
            nx, ny = x + dx, y + dy
            if not ((0 <= nx < x_lim) and (0 <= ny < y_lim)):
                continue
            if (nx, ny, level) in seen:
                continue
            elif graph[nx][ny] == "X":
                continue
            elif graph[nx][ny] == str(N) and level==N-1:
                return dis[(x, y, level)] + 1
            elif graph[nx][ny] == str(level+1):
                nxy = (nx, ny, level+1)
                dis[nxy] = dis[(x, y, level)] + 1
                if nxy not in seen:
                    todo.append(nxy)
                    seen.add(nxy)
            else:
                nxy = (nx, ny, level)
                dis[nxy] = dis[(x, y, level)] + 1
                if nxy not in seen:
                    todo.append(nxy)
                    seen.add(nxy)
        del dis[(x, y, level)]
def finds():
    for i in range(H):
        for j in range(W):
            if graph[i][j] == "S":
                return (i, j, 0)

ans = bfs_gird(finds())
print(ans)

Python: from collections import deque

d = [(1, 0), (-1, 0), (0, 1), (0, -1)]


def bfs(n):
    global pos_x, pos_y
    while len(que) != 0:
        x, y = que.popleft()
        for dx, dy in d:
            if 0 <= x + dx < W and 0 <= y + dy < H:
                if meiz[x + dx][y + dy] == str(n):
                    pos_x = x + dx
                    pos_y = y + dy
                    # print(distance)
                    return distance[x][y] + 1
                elif meiz[x + dx][y + dy] != "X" and distance[x + dx][y + dy] == float("inf"):
                    distance[x + dx][y + dy] = distance[x][y] + 1
                    # print(distance)
                    que.append((x + dx, y + dy))


if __name__ == '__main__':
    H, W, N = list(map(int, input().split()))
    meiz = [input() for i in range(H)]

    pos_x = 0
    for tmp in meiz:
        if tmp.find("S") != -1:
            pos_y = tmp.find("S")
            break
        pos_x += 1

    ans = 0
    for i in range(1, N + 1):
        distance = [[float("inf") for i in range(W)] for i in range(H)]
        distance[pos_x][pos_y] = 0
        que = deque()
        que.append((pos_x, pos_y))
        # print(que)
        ans += bfs(i)

    print(ans)

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 range(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)]
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[starts.index(stage[y][x])] = y
			starts_x[starts.index(stage[y][x])] = x
		if stage[y][x] in goals:
			goals_y[goals.index(stage[y][x])] = y
			goals_x[goals.index(stage[y][x])] = x


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):
			ny = y + [1,-1,0,0][i]
			nx = x + [0,0,1,-1][i]
			
			if ny >= 0 and ny < h and nx >= 0 and nx < w:
				if bfs_map[ny][nx] == -1 and stage[ny][nx] != "x":
					bfs_map[ny][nx] = bfs_map[y][x]+1
					data_y.append(ny)
					data_x.append(nx)
			if bfs_map[goal_y][goal_x] != -1:
				sum += bfs_map[goal_y][goal_x]
				goal = True
				break

print(sum)