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 <map>
#include <queue>

using namespace std;

#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define MP make_pair

typedef pair<int, int> PII;

int h, w, n;
char maps[1000][1001];
int memo[1000][1000];

int serach(int y, int x, int num) {
	queue<PII> Q;
	int res = 0;
	REP(i, h) REP(j, w) memo[i][j] = -1;

	Q.push(MP(y, x));
	memo[y][x] = 0;
	while (! Q.empty()) {
		int dx[] = {0,1,0,-1}, dy[] = {1,0,-1,0};
		PII q = Q.front(); Q.pop();
		if (maps[q.first][q.second] == num + '0') {res = memo[q.first][q.second]; break;}

		REP(i, 4) {
			int nx = q.second + dx[i], ny = q.first + dy[i];
			if (! (nx >= 0 && nx < w && ny >= 0 && ny < h)) continue;
			if (maps[ny][nx] == 'X' || memo[ny][nx] > -1) continue;
			memo[ny][nx] = memo[q.first][q.second] + 1;
			Q.push(MP(ny, nx));
		}
	}

	return res;
}

int main() {
	int ans = 0;
	cin >> h >> w >> n;
	REP(i, h) scanf("%s", maps[i]);

	REP(i, h) REP(j, w) {
		if (maps[i][j] == 'S') ans += serach(i, j, 1);
		if (maps[i][j] >= '1' && maps[i][j] < n + '0') ans += serach(i, j, (maps[i][j] + 1) - '0');
	}
	cout << ans << endl;

	return 0;
}

C++: #include "bits/stdc++.h"

using namespace std;

//#define int long long

#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define REP(i, n) for (int i = 0; i < (n); i++)

#define pb push_back
#define VDEL(v, n) v.erase(v.begin() + (n))
#define ALL(v) v.begin(), v.end()

#define INTMAX 2147483647
#define INF 200000000
#define TINT(str) atoi(str.c_str())
#define TSTR(num) to_string(num)

typedef long long ll;
typedef pair<int, int> PII;
typedef vector<int> VI;
typedef vector<vector<int>> VII;

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

PII goal[10];
char k[1000][1000];
int fx, fy;
int H,W;

int BFS(int x, int y)
{
    VII cost;
    cost = VII(H, VI(W, INT_MAX));

    cost[fx][fy] = 0;

    queue<PII> q;

    q.push(make_pair(fx, fy));

    while(!q.empty())
    {
        PII now = q.front();
        q.pop();
        int nx = now.first;
        int ny = now.second; 

        if(nx == x && ny == y)
        {
            return cost[nx][ny];
        }

        REP(i, 4)
        {
            if(nx + dx[i] >= H ||
            nx + dx[i] < 0) continue;
            if(ny + dy[i] >= W || 
            ny + dy[i] < 0) continue;

            if(k[nx + dx[i]][ny + dy[i]] != 'X')
            {
                if(cost[nx + dx[i]][ny + dy[i]] > 
                cost[nx][ny] + 1)
                {
                    cost[nx + dx[i]][ny + dy[i]] =
                        cost[nx][ny] + 1;
                    q.push(make_pair(nx + dx[i], ny + dy[i]));
                }
            }
        }
    }

    return -1;
}

signed main()
{
    int N;
    cin >> H >> W >> N;

    char str[1001];
    REP(h, H)
    {
        scanf("%s", str);
        REP(w, W)
        {
            k[h][w] = str[w];
            if(k[h][w] == 'S')
            {
                fx = h;
                fy = w;
            }
            if(k[h][w] != '.' &&
                k[h][w] != 'X')
            {
                goal[k[h][w] - '1'] = make_pair(h, w);
            }
        }
    }
    int ans = 0;

    REP(i, N)
    {
        ans += BFS(goal[i].first, goal[i].second);
        fx = goal[i].first;
        fy = goal[i].second;
    }

    cout << ans << endl;

    return 0;
}

C++: #include<iostream>
#include<queue>
#include<string.h>
using namespace std;
int n,m,sum,ti,sx,sy,dx[5]= {1,0,-1,0},dy[5]= {0,-1,0,1},ans=0,l,visited[1002][1002];
char mapp[1002][1002];
struct k
{
    int x,y,nowti,time;
} nainao[15];
queue<k> q;

int bfs(int nowsum)
{
    memset(visited,0,sizeof(visited));
    k a,b;
    a.x=sx,a.y=sy,a.nowti=nowsum,a.time=0;
    visited[a.x][a.y]=1;
    q.push(a);
    while(!q.empty())
    {
        b=q.front();
        q.pop();
        if(b.nowti==nowsum+1)
            break;
        for(int i=0; i<4; ++i)
        {
            k c=b;
            c.x+=dx[i],c.y+=dy[i];
            if(c.x>=0&&c.x<n&&c.y>=0&&c.y<m&&!visited[c.x][c.y]&&c.nowti+'0'!=mapp[c.x][c.y]&&mapp[c.x][c.y]!='X')
            {
                visited[c.x][c.y]=1;
                c.time++;
                q.push(c);
                continue;
            }
            if(c.x>=0&&c.x<n&&c.y>=0&&c.y<m&&c.nowti+'0'==mapp[c.x][c.y])
            {
                visited[c.x][c.y]=1;
                c.nowti++,c.time++;
                q.push(c);
            }
        }
    }
    return b.time;
}

int main()
{
    while(cin>>n>>m>>sum)
    {
        ans=0;
        for(int i=0; i<n; ++i)
            for(int j=0; j<m; ++j)
            {
                cin>>mapp[i][j];
                if(mapp[i][j]=='S')
                {
                    nainao[0].x=i,nainao[0].y=j;
                }
                else if(mapp[i][j]=='1')
                {
                    nainao[1].x=i,nainao[1].y=j;
                }
                else if(mapp[i][j]=='2')
                {
                    nainao[2].x=i,nainao[2].y=j;
                }
                else if(mapp[i][j]=='3')
                {
                    nainao[3].x=i,nainao[3].y=j;
                }
                else if(mapp[i][j]=='4')
                {
                    nainao[4].x=i,nainao[4].y=j;
                }
                else if(mapp[i][j]=='5')
                {
                    nainao[5].x=i,nainao[5].y=j;
                }
                else if(mapp[i][j]=='6')
                {
                    nainao[6].x=i,nainao[6].y=j;
                }
                else if(mapp[i][j]=='7')
                {
                    nainao[7].x=i,nainao[7].y=j;
                }
                else if(mapp[i][j]=='8')
                {
                    nainao[8].x=i,nainao[8].y=j;
                }
                else if(mapp[i][j]=='9')
                {
                    nainao[9].x=i,nainao[9].y=j;
                }
            }
        for(int i=1; i<=sum; ++i)
        {
            while(!q.empty())
                q.pop();
            sx=nainao[i-1].x,sy=nainao[i-1].y;
            ans+=bfs(i);
        }
        cout<<ans<<endl;
    }
}