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 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):
    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: 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: H, W, N = map(int, input().split())
field = [list(input()) for i in range(H)]
node_posi = {}
Q = []

def search(start, goal):
	Q.append(start)
	while Q:
		x, y, c = Q.pop(0)
		searched[y][x] = 1
		
		if ([x, y, 0] == goal):
			return c
		
		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-1) and (ny >= 0 and ny <= H-1) and (searched[ny][nx] == 0) and (field[ny][nx] != 'X'):
				Q.append([nx, ny, c+1])

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

s =	'S123456789'
cost = 0
for i in range(len(node_posi)-1):
	Q.clear()
	searched = [[0]*W for i in range(H)]
	cost += search(node_posi[s[i]], node_posi[s[i+1]])
print(cost)

Python: import collections

def search(sy, sx, gy, gx):
    visited = [[False for j in range(W)] for i in range(H)]
    visited[sy][sx] = True
 
    dq = collections.deque()
    dq.append((0, sy, sx))
    while dq:
        cost, y, x = dq.popleft()
        if (y,x) == (gy, gx):
            return cost
        for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):
            ny = y + dy
            nx = x + dx
            if ny < 0 or ny >= H or nx < 0 or nx >= W:
                continue
            if visited[ny][nx] or cells[ny][nx] == 'X':
                continue
            dq.append((cost + 1, ny, nx))
            visited[ny][nx] = True

def main(H, W, N, cells):
    points = {}
    for i in range(H):
        for j in range(W):
            points[cells[i][j]] = (i, j)
    points['0'] = points['S']
    total = 0
    for i in range(1, N+1):
        sy, sx = points[str(i-1)]
        gy, gx = points[str(i)]
        total += search(sy, sx, gy, gx)
    print(total)
 
 
if __name__ == '__main__':
    H, W, N = map(int, input().split())

    cells = []
    for i in range(H):
        cells.append(input())
    main(H, W, N, cells)

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