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 isnew(done, a, i):
    if done[a[0]][a[1]] == i:
        return False
    else:
        return True


h, w, n = map(int, input().split())

arr = []

s = [0, 0]

done = [[0 for i in range(w)] for j in range(h)]

for i in range(h):
    a = input()
    for j in range(w):
        if a[j] == 'S':
            s = [i, j]
    arr.append(a)
    
step = 0
    
for i in range(1, n+1):
    pre = [s]
    now = []
    f = 0
    while f == 0:
        step += 1
        for j in range(len(pre)):
            if pre[j][0] != 0:
                p = arr[pre[j][0]-1][pre[j][1]]
                pp = [pre[j][0]-1, pre[j][1]]
                if p == str(i):
                    s = pp
                    f = 1
                    break
                elif p != 'X' and isnew(done, pp, i):
                    now.append(pp)
                    done[pre[j][0]-1][pre[j][1]] = i

            if pre[j][0] != h-1:
                p = arr[pre[j][0]+1][pre[j][1]]
                pp = [pre[j][0]+1, pre[j][1]]
                if p == str(i):
                    s = pp
                    f = 1
                    break
                elif p != 'X' and isnew(done, pp, i):
                    now.append(pp)
                    done[pre[j][0]+1][pre[j][1]] = i

            if pre[j][1] != 0:
                p = arr[pre[j][0]][pre[j][1]-1]
                pp = [pre[j][0], pre[j][1]-1]
                if p == str(i):
                    s = pp
                    f = 1
                    break
                elif p != 'X' and isnew(done, pp, i):
                    now.append(pp)
                    done[pre[j][0]][pre[j][1]-1] = i

            if pre[j][1] != w-1:
                p = arr[pre[j][0]][pre[j][1]+1]
                pp = [pre[j][0], pre[j][1]+1]
                if p == str(i):
                    s = pp
                    f = 1
                    break
                elif p!= 'X' and isnew(done, pp, i):
                    now.append(pp)
                    done[pre[j][0]][pre[j][1]+1] = i
            

        pre = []
        for k in range(len(now)):
            temp = []
            for l in range(2):
                temp.append(now[k][l])
            pre.append(temp)
        now = []
                
                

print(step)

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

Python: from collections import deque

INF = 100000000
H, W, N = list(map(int, input().split()))
maze = [list(input()) for i in range(H)]

x = -1
for letters in maze:
    x += 1
    y = -1
    for letter in letters:
        y += 1
        if letter == "S":
            sx = x
            sy = y
        elif letter == str(N):
            gx = x
            gy = y

dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]


def bfs():
    count = 0
    backup = []
    for tmp_goal in range(1, N + 1):
        d = [[INF for i in range(W)] for j in range(H)]
        if tmp_goal == 1:
            q = deque([[sx, sy]])
            d[sx][sy] = 0
        else:
            q = deque([backup])
            d[backup[0]][backup[1]] = count

        while len(q) != 0:
            tmp_x, tmp_y = q.popleft()
            if maze[tmp_x][tmp_y] == str(tmp_goal):
                count = d[tmp_x][tmp_y]
                backup = [tmp_x, tmp_y]
                q.clear()
                break
            for j in range(0, 4):
                nx = tmp_x + dx[j]
                ny = tmp_y + dy[j]
                if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] != "X" and d[nx][ny] == INF:
                    q.append([nx, ny])
                    d[nx][ny] = d[tmp_x][tmp_y] + 1
    return count


if __name__ == '__main__':
    ans = bfs()
    print(ans)

Python: from collections import deque

H, W, N = map(int, input().split())
field = [list(input()) for i in range(H)]
node_posi = [0 for i in range(N+1)]

nodes = 'S123456789'
for i in range(H):
	for j in range(W):
		if field[i][j] in nodes:
			node_posi[nodes.index(field[i][j])] = [j, i]

cost = 0
for i in range(len(node_posi)-1):
	searched = [[-1]*W for i in range(H)]
	start, goal = node_posi[i], node_posi[i+1]
	Q = deque([start])
	searched[start[1]][start[0]] = 0
	goal_flag = False
	
	while Q and not goal_flag:
		x, y = Q.popleft()
		goal_flag = False

		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 and ny >= 0 and ny < H:
				if searched[ny][nx] == -1 and field[ny][nx] != 'X':
					Q.append([nx, ny])
					searched[ny][nx] = searched[y][x] + 1
					if ([nx, ny] == goal):
						cost += searched[ny][nx]
						goal_flag = True
						break

print(cost)