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<queue>
using namespace std;

string s[1000];
int h,w,n;
int dx[4]={-1,0,1,0};
int dy[4]={0,-1,0,1};

int bfs(int x,int y,int now)
{
	queue<pair<int,int>>Q;
	Q.push(make_pair(8,x*1000+y));
	while(!Q.empty())
	{
		pair<int,int>a=Q.front();Q.pop();
		int tx=a.second/1000,ty=a.second%1000;
		if(s[tx][ty]-'0'==now)
		{
			return a.first/10;
		}
		for(int r=0;r<4;r++)
		{
			if(abs(a.first%10-r)==2)continue;
			int sx=tx+dx[r];
			int sy=ty+dy[r];
			if(sx<0||sy<0||sx>=h||sy>=w||s[sx][sy]=='X')continue;
			Q.push(make_pair((a.first/10+1)*10+r,sx*1000+sy));
		}
	}
	return 1<<26;
}

int main()
{
	cin>>h>>w>>n;
	for(int i=0;i<h;i++)cin>>s[i];
	int c=0;
	pair<int,int> pr[9];
	for(int i=0;i<h;i++)
	{
		for(int j=0;j<w;j++)
		{
			if(s[i][j]=='S')
			{
				pr[0]=make_pair(i,j);
			}
			else if(s[i][j]>='0'&&s[i][j]<='8')
			{
				pr[s[i][j]-'0']=make_pair(i,j);
			}
		}
	}
	for(int i=1;i<=n;i++)
	{
		c+=bfs(pr[i-1].first,pr[i-1].second,i);
	}
	cout<<c<<endl;
	return 0;
}

C++: #include<iostream>
#include<queue>
using namespace std;
typedef pair<int, int> P;
int bfs();
int INF=1000000;
int h,w,n;
int sx,sy;
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
int d[1111][1111];
int ans=0;
char life='0';
char mapp[1111][1111];
int main(){

  cin>>h>>w>>n;
  for(int i=0;i<h;i++){
    for(int j=0;j<w;j++){
      cin>>mapp[i][j];
      if(mapp[i][j]=='S'){
	sy=i;
	sx=j;
      }      
    }
  }
  for(int i=1;i<n+1;i++){
    life++;
    ans+=bfs();
  }
  cout<<ans<<endl;
}
int bfs(){
  queue<P> que;
  que.push(P(sy,sx));
  for(int i=0;i<h;i++){
    for(int j=0;j<w;j++){
      d[i][j]=INF;
    }
  }
  d[sy][sx]=0;
  while(que.size()){
    P p=que.front();
    que.pop();
    if(mapp[p.first][p.second]==life){
      sy=p.first;
      sx=p.second;
      break;
    }
    for(int i=0;i<4;i++){
      int ny=p.first+dy[i];
      int nx=p.second+dx[i];
      if(0<=nx && nx<w && 0<=ny && ny<h && mapp[ny][nx]!='X' && d[ny][nx]==INF){
	que.push(P(ny,nx));
	d[ny][nx]=d[p.first][p.second]+1;
      }
    }
  }
  return d[sy][sx];
}

C++: #include<iostream>
#include<algorithm>
#include<map>
using namespace std;
#define MAX 1001

int h, w, n;
char city[MAX][MAX];
int step[10];
int direc1[4] = { -1,0,1,0 }, direc2[4] = { 0,1,0,-1 };

void dfs(char (&nowcity)[MAX][MAX], int nowstep, bool find, int nowi, int nowj, int nowpower, map<int, int> visited) {
	if (find) {
		if (step[nowpower-1] == -1) {
			step[nowpower-1] = nowstep;
		}
		else
		{
			step[nowpower-1] = min(step[nowpower-1], nowstep);
		}
		return;
	}
	if (step[nowpower] != -1) {
		if (nowstep >= step[nowpower]) {
			return;
		}
	}
	for (int i = 0; i < 4; i++) {
		if (nowi + direc1[i] >= 0 && nowi + direc1[i] < h&&nowj + direc2[i] >= 0 && nowj + direc2[i] < w) {

			if (nowcity[nowi + direc1[i]][nowj + direc2[i]] == '.') {
				if (!visited[(nowi + direc1[i]) * w + nowj + direc2[i]]) {
					visited[(nowi + direc1[i]) * w + nowj + direc2[i]]=1;
					dfs(nowcity, nowstep + 1, false, nowi + direc1[i], nowj + direc2[i], nowpower, visited);
				}	
			}
			else if (nowcity[nowi + direc1[i]][nowj + direc2[i]] >= '0'&&nowcity[nowi + direc1[i]][nowj + direc2[i]] <= '9')
			{
				int num = nowcity[nowi + direc1[i]][nowj + direc2[i]] - '0';
				if (nowpower == num) {					
					//nowcity[nowi + direc1[i]][nowj + direc2[i]] = '.';
					/*visited.clear();
					visited[(nowi + direc1[i]) * w + nowj + direc2[i]] =1;*/
					dfs(nowcity, nowstep + 1, true, nowi + direc1[i], nowj + direc2[i], nowpower,visited);
				}
				else {
					if (!visited[(nowi + direc1[i]) * w + nowj + direc2[i]]) {
						visited[(nowi + direc1[i]) * w + nowj + direc2[i]] =1;
						dfs(nowcity, nowstep + 1, false, nowi + direc1[i], nowj + direc2[i], nowpower,visited);
					}				
				}
			}
		}
	}
}



int main() {
	cin >> h >> w >> n;
	int nowi[10], nowj[10];
	
	for (int i = 0; i < h; i++)
	{
		for (int j = 0; j < w; j++)
		{
			cin >> city[i][j];
			if (city[i][j] == 'S') {
				nowi[0] = i;
				nowj[0] = j;
				city[i][j] = '.';
			}
			if (city[i][j] >= '0'&&city[i][j] <= '9') {
				nowi[city[i][j] - '0'] = i;
				nowj[city[i][j] - '0'] = j;
			}
		}
	}
	for (int i = 0; i < 10; i++) {
		step[i] = -1;
	}
	map<int, int>visited;
	for (int i = 0; i < n; i++) {
		visited.clear();
		visited[nowi[i] * w + nowj[i]] = 1;
		dfs(city, 0, false, nowi[i], nowj[i], i+1, visited);
	}
	int sum=0;
	for (int i = 0; i < n; i++) {
		sum += step[i];
	}
	cout << sum << endl;
	//system("pause");
	return 0;
}

C++: #include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;

const int maxn = 1010;
typedef struct Point
{
    int x, y, t, n;
    Point(int _x, int _y, int _t)
    {
        x = _x, y =_y, t = _t;
    }
};

char a[maxn][maxn];
bool vis[maxn][maxn];
int W, H, N;
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
int data[16][2];

int BFS(int sx, int sy, int ex, int ey)
{
    queue<Point> que;
    que.push(Point(sx, sy, 0));
    memset(vis, 0, sizeof(vis));
    vis[sx][sy] = 1;

    while(!que.empty())
    {
        Point p = que.front(); que.pop();
        //cout<<"p.t: "<<p.t<<endl;
        if(p.x == ex && p.y == ey) return p.t;

        for(int i = 0; i < 4; i++)
        {
            int nx = p.x + dx[i];
            int ny = p.y + dy[i];
            //cout<<nx<<"          "<<ny<<" "<<vis[nx][ny]<<endl;
            if(nx >= 0 && nx < H && ny >= 0 && ny < W && a[nx][ny] != 'X' && vis[nx][ny] == 0)
            {
                //cout<<"nx: "<<nx<<" ny: "<<ny<<" nn "<<nn<<" a[nx][ny] "<<a[nx][ny]<<endl;
                que.push(Point(nx, ny, p.t + 1));
                vis[nx][ny] = 1;
            }
        }
    }
  /*  for(int i = 0; i < H; i++)
    {
        for(int j = 0; j  < W; j++)
            cout<<vis[i][j];
        cout<<endl;
    }*/
    return 0;
}

int main()
{
    //FILE *f = fopen("data.txt","rb");
    scanf("%d%d%d", &H, &W, &N)
    
        int sx, sy, ans = 0;

        for(int i = 0; i < H; i++)
            scanf("%s",a[i]);

        for(int i = 0; i < H; i++)
            for(int j = 0; j  < W; j++)
                if(a[i][j] == 'S')  {data[0][0] = i, data[0][1] =j; a[i][j] = '.'; break;}
                else if( isdigit(a[i][j]) )
                {
                    int index = a[i][j] - '0';
                    data[index][0] = i;
                    data[index][1] = j;
                }
        for(int i = 0; i < N; i++)
        {
            ans += BFS(data[i][0], data[i][1],  data[i+1][0], data[i+1][1]);
        }
        printf("%d\n",ans);
    
    return 0;
}