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<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int map[1005][1005];
struct node{
	int x,y,time;
}s[10],p;
queue<node> q;
int vis[1005][1005];
int n,m,T;
int dir[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int bfs(int a,int b){
	while(!q.empty())
		q.pop();
	q.push(s[a]);
	memset(vis,0,sizeof vis);
	vis[s[a].x][s[a].y]=1;
	while(!q.empty()){
		p=q.front();
		q.pop();
		int x=p.x,y=p.y,time=p.time;
		for(int i=0;i<4;i++){
			int x1=x+dir[i][0],y1=y+dir[i][1];
			if(x1<=0||y1<=0||x1>n||y1>m||vis[x1][y1]||map[x1][y1])
				continue ;
			if(x1==s[b].x&&y1==s[b].y)
				return time+1;
			vis[x1][y1]=1;
			p.x=x1,p.y=y1,p.time=time+1;
			q.push(p);
		}
	}
}
int main()
{
	scanf("%d%d%d",&n,&m,&T);
	for(int i=1;i<=n;i++){
		scanf("\n");
		for(int j=1;j<=m;j++){
			char c;
			c=getchar();
			if(c=='S')
				s[0].x=i,s[0].y=j;
			if(c=='X')
				map[i][j]=1;
			if(c>='1'&&c<='9')
				s[c-'0'].x=i,s[c-'0'].y=j;
		}
	}
	int time=0;
	for(int i=0;i<T;i++)
		time+=bfs(i,i+1);
	printf("%d\n",time);
}

C++: 
#include <iostream>   
#include<stack> 
#include<queue> 
#include<string> 
#include <math.h>
using namespace std;

const int MAX_H = 1000;
const int MAX_W = 1000;
const int a = 100000000;

typedef pair<int, int> P;

int H = 0, W = 0, N = 0; 
 
int food[11][2];
char cheese[MAX_H][MAX_W] = {0}; 
int r[MAX_H][MAX_W]; 
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; 

int search(int &sx, int &sy, int &ex, int &ey)
{
 
    P p;
    queue<P> que;
    for(int i=0; i<H; i++)
   {
        for(int j=0; j<W; j++)
       {
           r[i][j] = a;

        }
    }
    que.push(P(sx,sy));
    r[sx][sy] = 0;

    while(que.size())
   {  
        p = que.front();
        que.pop();
        if(p.first == ex && p.second == ey)
			break;
	

	    for(int i=0; i<4; i++)
	   {
		    int xn = p.first + dx[i];
		    int yn = p.second + dy[i];


		    if(xn >= 0 && xn < H && yn >= 0 && yn < W && cheese[xn][yn]!='X' && r[xn][yn] == a )
		   {
			    que.push(P(xn,yn));
			    r[xn][yn] = r[p.first][p.second] + 1;
		    }
	    }

	}
	return r[ex][ey];
}

int main()
{
	int dis = 0;
    cin >> H >> W >> N;
    for(int i=0; i<H; i++)
   {
        for(int j=0; j<W; j++)
       {
          cin >> cheese[i][j];
          if(cheese[i][j] == 'S')
         {
             food[0][0] = i;
             food[0][1] = j;
             cheese[i][j] = '.';
          }
          if(cheese[i][j]>48&&cheese[i][j]<58)
         {
             int num = cheese[i][j] - 48;  
             food[num][0] = i;
             food[num][1] = j;
          }
       }
    }
   

    for(int i=0; i<N; i++)
   {
       dis += search(food[i][0], food[i][1], food[i+1][0], food[i+1][1]); 
    }
    
	cout << dis << endl;
    return 0;
}

C++: #include<iostream>
using namespace std;
#define INF 10000000
#define rep(i,n) for(int i=0;i<(n);i++)
int dx[]={1,0,-1,0};
int dy[]={0,1,0,-1};
int h,w,n;
char m[1000][1000];

int bellmanFord(int s){
	static int d[1000][1000];
	rep(i,h)rep(j,w)
		if(m[i][j]=='0'+s)d[i][j]=0;
		else d[i][j]=INF;
	while(1){
		rep(i,h)rep(j,w)rep(k,4){
			int ny=i+dy[k], nx=j+dx[k];
			if(ny<0||h<=ny||nx<0||w<=nx||m[ny][nx]=='X')continue;
			if(d[i][j]+1 < d[ny][nx]){
				d[ny][nx] = d[i][j]+1;
				if(m[ny][nx]=='0'+s+1)return d[ny][nx]; 
			}
		}
	}
	return -1;
}
int main(){
	cin>>h>>w>>n;
	rep(i,h)rep(j,w){
		cin>>m[i][j];
		if(m[i][j]=='S')m[i][j]='0';
	}
	int ans=0;
	for(int i=0;i<n;i++)ans += bellmanFord(i);
	cout<<ans<<endl;
}

C++: #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <cstring>
#include <sstream>
#include <cassert>
using namespace std;
static const double EPS = 1e-10;
typedef long long ll;
typedef pair<int,int> PI;
#define rep(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
int dx[]={0,1,0,-1},dy[]={1,0,-1,0};

typedef struct{
  int x,y;
  int cost;
  int ch;
  int hp(){
    int ret=1;
    rep(i,9)ret+=(ch>>i&1);
    return ret;
  }
}mouse;

main(){
  int h,w,n;
  cin>>h>>w>>n;
  char ku[h][w];
  rep(i,h)cin>>ku[i];

  int sx,sy;
  rep(i,h)rep(j,w)if(ku[i][j]=='S')sx=i,sy=j;

  queue<mouse> Q;
  set<pair<PI,int> > app;
  Q.push((mouse){sx,sy,0,0});
  app.insert(mp(mp(sx,sy),0));

  int ans=0;
  while(!Q.empty()){
    //    cout<<Q.size()<<endl;
    mouse t=Q.front();Q.pop();
    int cx=t.x,cy=t.y,cost=t.cost;
    int ch=t.ch;
    if(ch==(1<<n)-1){
      ans=cost;
      break;
    }

    app.insert(mp(mp(cx,cy),ch));

    rep(i,4){
      int nx=cx+dx[i],ny=cy+dy[i];
      if(nx<0 || nx>=h || ny<0 || ny>=w)continue;
	 if(ku[nx][ny]=='X')continue;
	 int nch=ch;
	 if(ku[nx][ny]<='9' && ku[nx][ny]>='1'){
	   int num=ku[nx][ny]-'1';
	   if(num+1<=t.hp()){
	     nch=ch|(1<<num);
	   }
	 }
	 if(app.count(mp(mp(nx,ny),nch)))continue;
	 Q.push((mouse){nx,ny,cost+1,nch});
	 app.insert(mp(mp(nx,ny),nch));
    }
  }
  cout<<ans<<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; };

LL H, W, N;
std::string field[1123];
LL Sx, Sy, xy[11];
LL 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 < 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;
}