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 bfs(count, x, y, cheese):
    queue = [(count,x,y)]
    while len(queue)>0:
        tempc,tempx,tempy = queue.pop(0)
        print(tempc,tempx,tempy)
        if geo[tempx][tempy] == cheese:
            return tempc,tempx,tempy
        for i in range(4):
            neox = tempx+dx[i]
            neoy = tempy+dy[i]
            if canGoTo(neox,neoy):
                if (tempc+1,neox,neoy) not in queue:
                    queue.append((tempc+1,neox,neoy))

    return (-1,-1,-1)

def canGoTo(x,y):
    if 0<=x<H and 0<=y<W:
        return not visited[x][y]
    return False

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

data = input().split(' ')
H,W,N = map(int, data)

#maps
geo = [[None for i in range(W)] for j in range(H)]
visited = [[False for i in range(W)] for j in range(H)]

x,y=-1,-1
for i in range(H):
    line = input()
    for j in range(W):
        p = line[j:j+1]
        geo[i][j] = p
        if p == 'X':
            visited[i][j] = True
        elif p == 'S':
            x,y, = i,j
            
count = 0
for n in range(1,N+1):
    count,x,y = bfs(count,x,y,str(n))
print(count)

Python: from collections import deque
h,w,n = map(int,input().split())
factrys = [None] * (n + 1)
ss = ["X" * (w + 2)]
append = ss.append
for i in range(h):
  s = "X" + input() + "X"
  if "S" in s:
    factrys[0] = (i + 1, s.index("S"))
  for j in range(len(s)):
    if s[j] != 'S' and s[j] != '.' and s[j] != 'X':
      factrys[int(s[j])] = (i + 1, j)
  append(s)
append("X" * (w + 2))

def bfs(i):
  mp = [[-1] * (w + 2) for j in range(h + 2)]
  x,y = factrys[i]
  que = deque()
  append = que.append
  popleft = que.popleft
  append((x, y))
  for count in range(10000000):
    sz = len(que)
    for loop in range(sz):
      (x,y) = popleft()
      if ss[x][y] == 'X' or not mp[x][y] is -1:
        continue
      if (x,y) == factrys[i + 1]:
        return count
      mp[x][y] = count
      append((x + 1, y))
      append((x - 1, y))
      append((x, y + 1))
      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())
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

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)

C++: #include<iostream>
#include<queue>
#include<ctype.h>
#include<cstdio>
using namespace std;
int H,W,sum,count;
int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
struct node
{
	int x,y;
	int step;
	int color;
	char data;
}*map,now,next;
void BFS(int x,int y)
{
	queue<node>q;
	q.push(map[x*W+y]);
	while(!q.empty())
	{
		now=q.front();
		q.pop();
		for(int i=0;i<4;i++)
		{
			next.x=now.x+dir[i][0];
			next.y=now.y+dir[i][1];
			if(next.x>=0&&next.y>=0&&next.x<H&&next.y<W&&map[next.x*W+next.y].data!='X'&&map[next.x*W+next.y].color<count)
			{
				map[next.x*W+next.y].step=now.step+1;
				if(int(map[next.x*W+next.y].data-'0')==count)
				{
					count++;
					map[next.x*W+next.y].data='.';
					if(count>sum)
					{
						cout<<map[next.x*W+next.y].step<<endl;
						return;
					}
					map[next.x*W+next.y].color=count;
					BFS(next.x,next.y);
				}
				else
				{
					map[next.x*W+next.y].color=count;
					q.push(map[next.x*W+next.y]);
				}
				if(count>sum)return;
			}
		}
	}
}
int main()
{
	//freopen("01.txt","r",stdin);
	while(cin>>H>>W>>sum)
	{
		map=new node[H*W];
		for(int i=0;i<H;i++)
		{
			for(int j=0;j<W;j++)
			{
				cin>>map[i*W+j].data;
				map[i*W+j].x=i;
				map[i*W+j].y=j;
				map[i*W+j].color=0;
				if(map[i*W+j].data=='S')
				{
					now.x=i;
					now.y=j;
				}
			}
		}
		count=1;
		map[now.x*W+now.y].step=0;
		map[now.x*W+now.y].color=1;
		map[now.x*W+now.y].data='.';
		BFS(now.x,now.y);
	}
	return 0;
}

C++: #include<stdio.h>
#include<iostream>
#include<queue>
using namespace std;
int m[1002][1002]={0},p[1002][1002]={0};
struct r{
int g,l,g2,l2;
};
int main(){
int h,w,n,i,j,a,b[2];
b[0]=1;
b[1]=-1;
char c[2001];
r gl;
queue<r> q;
cin>>h>>w>>n;
for(i=0;i<=h+1;i++){
m[i][0]=-1;
m[i][w+1]=-1;
}
for(i=0;i<=w+1;i++){
m[0][i]=-1;
m[h+1][i]=-1;
}
for(i=1;i<=h;i++){
	scanf("%s",c);
	for(j=1;j<=w;j++){
		a=c[j-1];
		if(a>=49&&a<=57){m[i][j]=a-48;}
		if(c[j-1]=='X'){m[i][j]=-1;}
		if(c[j-1]=='S'){
		gl.g=i;
		gl.g2=j;
		gl.l=0;
		gl.l2=1;
		q.push(gl);
		}
	}
}
while(!q.empty()){
	gl=q.front();
	q.pop();
	if(m[gl.g][gl.g2]==gl.l2){
		gl.l2++;
		if(gl.l2==n+1){
			break;
		}
		while(!q.empty())q.pop();
	}
	p[gl.g][gl.g2]=gl.l2;
gl.l++;
	for(i=0;i<2;i++){
		if(m[gl.g+b[i]][gl.g2]!=-1 && p[gl.g+b[i]][gl.g2]!=gl.l2){
			gl.g+=b[i];
			q.push(gl);
			gl.g-=b[i];
		}
		if(m[gl.g][gl.g2+b[i]]!=-1 && p[gl.g][gl.g2+b[i]]!=gl.l2){
			gl.g2+=b[i];
			q.push(gl);
			gl.g2-=b[i];
		}
	}
}
cout<<gl.l<<endl;
return 0;
}