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<string>
#include<vector>
#include<string.h>
#include<queue>
using namespace std;

typedef pair<int,int> COR;

int H,W,C;
vector<string> M;
int INF= 100000;

int cost[10][10];
bool come[1000][1000];

int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};


void solve(){

	for(int i=0;i<10;i++)
		for(int j=0;j<10;j++)
			cost[i][j]=INF;

	M.clear();
	vector<pair<int,int> > V;
	
	for(int i=0;i<H;i++){
		string h;
		cin>>h;
		for(int j=0;j<h.size();j++)
			if(isdigit(h[j]) || h[j]=='S')
				V.push_back(make_pair(i,j));
			
		M.push_back(h);
	}

	int now;
	for(int i=0;i<V.size();i++){
		if(isdigit(M[V[i].first][V[i].second]))
			now=M[V[i].first][V[i].second]-'0';

		if(M[V[i].first][V[i].second]=='S')
			now=0;

		memset(come,false,sizeof(come));
		queue<pair<COR,int> > Q;
		Q.push(make_pair(V[i],0));
		int count=0;
		while(!Q.empty() && count<C+1){
			pair<COR,int> p=Q.front();
			Q.pop();
			int y=p.first.first,x=p.first.second,c=p.second;
			if(y<0 || x<0 || y>=H || x>=W ||come[y][x] || M[y][x]=='X')
				continue;
			come[y][x]=true;
			if(isdigit(M[y][x])){
				cost[now][M[y][x]-'0']=min(c,cost[now][M[y][x]-'0']);
				count++;
			}
			if(M[y][x]=='S'){
				count++;
				cost[now][0]=min(c,cost[now][0]);
			}

			for(int r=0;r<4;r++)
				Q.push(make_pair(make_pair(y+dy[r],x+dx[r]),c+1));
		}
	}

	int res=0;

	for(int i=0;i<C;i++)
		res+=cost[i][i+1];
	cout<<res<<endl;
}

int main()
{
	while(cin>>H>>W>>C){
		solve();
	}
	return 0;
}

C++: #include<bits/stdc++.h>
using namespace std;
using ll=long long;

const int INF=1<<30;

vector<int> dx={1, 0, -1, 0}, dy={0, 1, 0, -1};

int main(){
    int H, W, N; cin >> H >> W >> N;
    int sx, sy;
    vector<pair<int, int>> plant(N);
    vector<vector<char>> data(H, vector<char>(W));
    for(int i=0; i<H; i++){
        for(int j=0; j<W; j++){
            cin >> data[i][j];
            if(data[i][j] == 'S') sx=i, sy=j;
            for(int k=0; k<N; k++){
                if(data[i][j]-'0' == k+1){
                    plant[k]=make_pair(i, j);
                }
            }
        }
    }
    ll res=0;
    vector<vector<int>> dist(H, vector<int>(W, -1));
    dist[sx][sy]=0;
    queue<pair<int, int>> que;
    que.push(make_pair(sx, sy));
    for(int i=-1; i<N-1; i++){
        if(i > -1){
            tie(sx, sy)=plant[i];
            dist.assign(H, vector<int>(W, -1));
            dist[sx][sy]=0;
            que.push(make_pair(sx, sy));
        }
        while(!que.empty()){
            int x, y;
            tie(x, y)=que.front();
            que.pop();
            for(int j=0; j<4; j++){
                int nx=x+dx[j];
                int ny=y+dy[j];
                if(nx<0 || nx>=H || ny<0 || ny>=W) continue;
                if(dist[nx][ny] != -1) continue;
                if(data[nx][ny] == 'X') continue;
                dist[nx][ny]=dist[x][y]+1;
                que.push(make_pair(nx, ny));
            }
        }
        int gx, gy;
        tie(gx, gy)=plant[i+1];
        res+=dist[gx][gy];
    }
    cout << res << endl; 
    return 0;
}

C++: #include<iostream>
#include<cstdio>
#include<queue>
#include<utility>
#include<cstring>
using namespace std;
char map[1005][1005];
bool vis[1005][1005];
int dx[]={0,0,-1,1};
int dy[]={1,-1,0,0};
int sx,sy;
int h,w;
int bfs(int n){
	memset(vis,false,sizeof(vis));
	queue<pair<pair<int,int>,int> >que;
	que.push(make_pair(make_pair(sx,sy),0));
	while(!que.empty()){
		pair<int,int>now=que.front().first;
		int cnt=que.front().second;
		que.pop();
		if(map[now.first][now.second]==n+48){
			sx=now.first;
			sy=now.second;
			return cnt;
		}
		for(int i=0;i<4;i++){
			int _x=now.first+dx[i];
			int _y=now.second+dy[i];
			if(_x<0||_y<0||_x>=h||_y>=w||map[_x][_y]=='X'||vis[_x][_y]){
				continue;
			}
			vis[_x][_y]=true;
			que.push(make_pair(make_pair(_x,_y),cnt+1));
		}
	}
}
int main(){
	int n;
	while(cin>>h>>w>>n){
		memset(map,0,sizeof(map));
		for(int i=0;i<h;i++){
			scanf("%s",map[i]);
		}
		for(int i=0;i<h;i++){
			for(int j=0;j<w;j++){
				if(map[i][j]=='S'){
					sx=i;
					sy=j;
					map[i][j]=='.';
					break;
				}
			}
		}
		int count=0;
		for(int k=1;k<=n;k++){
			count+=bfs(k);
		}
		cout<<count<<endl;
	}
	return 0;
}

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;
}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==n){
      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]-'0';
	   if(num==t.ch+1){
	     nch=ch+1;
	   }
	 }
	 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;
}