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

C++: #include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
int h,w,n;
char map[1005][1005];
bool vis[1005][1005];
int dx[]={0,0,1,-1},dy[]={1,-1,0,0};
int cnt;
int f[1001*1001];

int BFS(int x,int y,int t)
{
	int m;
	memset(vis,0,sizeof vis);
	for(int i=1;i<=h;i++)
	{
		for(int j=1;j<=w;j++)
		{
			if(map[i][j]=='X')
			{
				vis[i][j]==1;
			}
		}
	}
	queue<int> q;
	q.push(x*1001+y);
	int xxx,yyy;
	while(!q.empty())
	{
		int xx=q.front()/1001,yy=q.front()%1001;
		q.pop();
		if(map[xx][yy]=='0'+t)
		{
			xxx=xx,yyy=yy;
			break;
		}
		for(int i=0;i<4;i++)
		{
			if(!vis[xx+dx[i]][yy+dy[i]]&&map[xx+dx[i]][yy+dy[i]]!='X')
			{
				q.push((xx+dx[i])*1001+yy+dy[i]);
				vis[xx+dx[i]][yy+dy[i]]=1;
				f[(xx+dx[i])*1001+yy+dy[i]]=xx*1001+yy;
			}
		}
	}
	m=1;
	int s=xxx*1001+yyy;
	while(f[s]!=x*1001+y)
	{
		m++;
		s=f[s];
	}
	return m;
}

int bfs(int f,int t)

{
	for(int i=1;i<=h;i++)
	{
		for(int j=1;j<=w;j++)
		{
			if(map[i][j]-'0'==f)
			{
				//cout<<i<<j;
				return(BFS(i,j,t));
			}
		}
	}
}



int main()
{
	cin>>h>>w>>n;
	cnt=0;
	memset(map,'X',sizeof map);
	for(int i=1;i<=h;i++)
	{
		for(int j=1;j<=w;j++)
		{
			cin>>map[i][j];
		}
	}
	for(int i=1;i<=h;i++)
	{
		for(int j=1;j<=w;j++)
		{
			if(map[i][j]=='S')
			{
				map[i][j]='0';
			}
		}
	}
	for(int i=0;i<n;i++)
		cnt+=bfs(i,i+1);
	cout<<cnt<<endl;
}

C++: #include "bits/stdc++.h"
#define MOD 1000000007
#define INF 11234567890
#define in std::cin
#define out std::cout
#define rep(i,N) for(LL i=0;i<N;++i)
typedef long long int LL;
typedef std::pair<LL, LL> P;
struct edge { LL to, cost; };

int H, W, N;
std::string field[1123];
int Sx, Sy, xy[10];
int ans;

LL d[1123456];
std::vector<edge>G[1123456];
void dijkstra(LL s)
{
	std::priority_queue<P, std::vector<P>, std::greater<P>>que;
	std::fill(d, d + H * W + 1, INF);
	d[s] = 0;
	que.push(P(0, s));
	while (!que.empty())
	{
		P p = que.top(); que.pop();
		LL v = p.second;
		if (d[v] < p.first) { continue; }
		rep(i, G[v].size())
		{
			edge e = G[v][i];
			if (d[e.to] > d[v] + e.cost)
			{
				d[e.to] = d[v] + e.cost;
				que.push(P(d[e.to], e.to));
			}
		}
	}
}

int main()
{
	in >> H >> W >> N;
	rep(i, H) { in >> field[i]; }

	rep(x, H)
	{
		rep(y, W)
		{
			if (field[x][y] == 'X') { continue; }
			if (field[x][y] == 'S') { Sx = x; Sy = y; }
			if (field[x][y] != '.') { xy[field[x][y] - '0'] = x*W + y; }
			if (x > 0)
			{
				if (field[x - 1][y] != 'X')
				{
					G[x*W + y].push_back({ (x - 1)*W + y,1 });
					G[(x - 1)*W + y].push_back({ x*W + y,1 });
				}
			}
			if (y > 0)
			{
				if (field[x][y - 1] != 'X')
				{
					G[x*W + y].push_back({ x*W + (y - 1),1 });
					G[x*W + (y - 1)].push_back({ x*W + y,1 });
				}
			}
			if (x < H - 1)
			{
				if (field[x + 1][y] != 'X')
				{
					G[x*W + y].push_back({ (x + 1)*W + y,1 });
					G[(x + 1)*W + y].push_back({ x*W + y,1 });
				}
			}
			if (y < W - 1)
			{
				if (field[x][y + 1] != 'X')
				{
					G[x*W + y].push_back({ x*W + (y + 1),1 });
					G[x*W + (y + 1)].push_back({ x*W + y,1 });
				}
			}
		}
	}
	dijkstra(Sx*W + Sy);
	rep(i, N)
	{
		ans += d[xy[i + 1]];
		dijkstra(xy[i + 1]);
	}

	out << ans << std::endl;
	return 0;
}

C++: #include <iostream>
#include <queue>
#include <vector>
using namespace std;
#define MAX 1000
const int INF = 1000000;
typedef pair<int,int> P;
int n,m;
char mp[MAX+1][MAX+1];

int bfs(int sy,int sx,int gy,int gx){
    int dx[4]={1,0,-1,0} , dy[4]={0,1,0,-1};
    int d[MAX][MAX];
    queue<P> q;
    
    for(int i = 0 ; i < n ; i++)
        for(int j = 0 ; j < m ; j++)
            d[i][j] = INF;
    
    q.push(P(sy,sx));
    d[sy][sx] = 0;
    
    while(q.size()){
        P p = q.front(); q.pop();
        if(p.first == gy && p.second == gx) break;
        
        for(int i = 0 ; i < 4 ; i++){
            int nx = p.first+dx[i];
            int ny = p.second+dy[i];
            
            if(0<=nx&&nx<n&&0<=ny&&ny<m&&d[nx][ny]==INF&&mp[nx][ny]!='X'){
                q.push(P(nx,ny));
                d[nx][ny] = d[p.first][p.second]+1;
            }
        }
    }

    return d[gy][gx];
}

int main(){
    int num;
    
    fill(mp[0],mp[MAX],'#');
    cin >> n >> m >> num;
    vector<P> v(num+1);
    
    for(int i = 0 ; i < n ; i++){
        for(int j = 0 ; j < m ; j++){
            cin >> mp[i][j];
            if(mp[i][j]=='S'){
                v[0].first = i;
                v[0].second = j;
            }
            if('1' <= mp[i][j] && mp[i][j] <= '9'){
                v[mp[i][j]-'0'].first = i;
                v[mp[i][j]-'0'].second = j;
            }
        }
    }
    
    int sum = 0;
    for(int i = 1 ; i < num+1 ; i++){
        sum += bfs(v[i-1].first,v[i-1].second,v[i].first,v[i].second);
    }
    cout << sum << endl;
    
    return 0;
}

C++: #include<bits/stdc++.h>
using namespace std;
#define forn(i,n) for(int i=0;i<int(n);i++)
typedef pair<int,int> P;
#define fi first
#define se second
char maze[1000][1000];
int d[1000][1000];
int w,l,n,ans=0;
int sx,sy,ex,ey;
#define INF 100000
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
int bfs(int times){//return partial ans, assign coordinate
	queue<P> que;
	forn(i,l) forn(j,w) d[i][j]=INF;
	que.push(P(sx,sy));
	d[sx][sy]=0;
	while(que.size()){
		P p = que.front(); que.pop();
		if(maze[p.fi][p.se]=='1'+times){
			sx=p.fi;
			sy = p.se;
			maze[p.fi][p.se] = '.';
			return d[sx][sy];
		}
		forn(i,4){
			int tx = p.fi+dx[i],ty=p.se+dy[i];
			if(tx>=0&&tx<l&&ty>=0&&ty<w&&maze[tx][ty]!='X'&&d[tx][ty]==INF) {
				d[tx][ty] = d[p.fi][p.se]+1;
				que.push(P(tx,ty));
			}
		}
	}
}
int main(){
	cin>>l>>w>>n;//l is x, w is y
	forn(i,l)
		forn(j,w){
		cin>>maze[i][j];
		if(maze[i][j]=='S'){
			sx = i;
			sy = j;
			maze[i][j]= '.';
		}
		}
	forn(i,n){
		ans+=bfs(i);
	}
	cout<<ans<<endl;
}