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 <bits/stdc++.h>
#define FOR(i, a, b) for(int i=(a); i<(b); i++)
#define REP(i, n) FOR(i, 0, n)
#define all(x) (x).begin(), (x).end()
#define bit(x) (1L << (x))
using ll = long long;
using namespace std;

template<typename T>
vector<T> make_v(size_t a,T b){return vector<T>(a,b);}
 
template<typename... Ts>
auto make_v(size_t a,Ts... ts){
    return vector<decltype(make_v(ts...))>(a,make_v(ts...));
}

int main() {
    int h, w, n; cin >> h >> w >> n;
    auto g = make_v(h, w, '0');

    int fy, fx;
    REP(i, h)REP(j, w) {
        cin >> g[i][j];
        if (g[i][j] == 'S') {
            fy = i; fx = j;
        }
    }

    constexpr int dy[] = {-1, 0, 1, 0}, dx[] = {0, -1, 0, 1};
    auto in = [&](int i, int j) {
        return 0 <= i && i < h && 0 <= j && j < w;
    };
    
    function<int(int, int, int)> solve = [&](int i, int sy, int sx) {
        if (i == n) return 0;

        using p = pair<int, int>;
        queue<p> q;
        auto v = make_v(h, w, -1);
        
        q.push({sy, sx});
        v[sy][sx] = 0;

        while (!q.empty()) {
            auto now = q.front(); q.pop();
            int y = now.first, x = now.second;
            
            if (g[y][x] == '0' + i + 1) {
                return v[y][x] + solve(i + 1, y, x);
            }

            REP(i, 4) {
                int ny = y + dy[i], nx = x + dx[i];
                if (in(ny, nx) && g[ny][nx] != 'X' && v[ny][nx] == -1) {
                    q.push({ny, nx});
                    v[ny][nx] = v[y][x] + 1;
                }
            }
        }
        
        return -1; // error
    };

    cout << solve(0, fy, fx) << endl;

    return 0;
}

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

struct node {
    int x, y, steps;
};

const int dx[4] = { 1, 0, -1, 0 };
const int dy[4] = { 0, 1, 0, -1 };
int n, m, map[1005][1005], vis[1005][1005], num, stx, sty;

int bfs() {
    int tot = 0;
    for (int i = 1; i <= num; i++) {
        memset(vis, 0x3f, sizeof vis);
        vis[stx][sty] = 0;
        queue<node> q;
        q.push({ stx, sty, 0 });
        while (!q.empty()) {
            node cnt = q.front(); q.pop();
            if (map[cnt.x][cnt.y] == '0' + i) {
                tot += cnt.steps;
                stx = cnt.x; sty = cnt.y;
                break;
            }
            for (int k = 0; k < 4; k++) {
                int nx = cnt.x + dx[k];
                int ny = cnt.y + dy[k];
                if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue;
                if (map[nx][ny] == 'X' || vis[nx][ny] <= cnt.steps + 1) continue;
                vis[nx][ny] = cnt.steps + 1;
                q.push({ nx, ny, cnt.steps + 1 });
            }
        }
    }
    return tot;
}

int main() {
    scanf("%d %d %d", &n, &m, &num);
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++) {
            char ch = getchar();
            if (ch == '\n') ch = getchar();
            if (ch == 'S') { stx = i; sty = j; }
            map[i][j] = ch;
        }
    cout << bfs() << endl;
    return 0;
}

C++: #include <cstdio>
#include <iostream>
#include <queue>
#include <map>  
using namespace std;
int ans = 0;

typedef pair<int,int >P;
int gh=0, gw=0;
char c[1000][1000];
int d[1000][1000];
int mh[4] = { 1,0,-1,0 };
int mw[4] = { 0,1,0,-1 };
char hijou[9] = { '1','2','3','4','5','6','7','8','9' };
void judge(int h, int w, int g) {
	queue<P> que;
	que.push(P(h,w));
	while (que.size()) {
		P p = que.front(); que.pop();
		if (c[p.first][p.second] == hijou[g])
		{
			gh = p.first;
			gw = p.second;
			ans+=d[p.first][p.second];
			break;
		}
		for (int i = 0; i < 4; i++) {
			int  nh = p.first + mh[i];
			int  nw = p.second + mw[i];
			if (nh >= 0 && nh < 1000 && nw >= 0 && nw < 1000 && d[nh][nw] == 500000 && c[nh][nw] != 'X') {
				d[nh][nw] = d[p.first][p.second] + 1;
				que.push(P(nh, nw));
			}
		}
	}
}
int main() {
	int h, w, n,sh,sw;
	for (int i = 0; i < 1000;i++){
		for (int j = 0; j < 1000; j++)
		{
			c[i][j] = 'X'; 
		}
	}
	cin >> h >> w >> n;
	for (int i = 0; i < h; i++) {
		for (int j = 0; j < w;j++){
			cin >> c[i][j];
			if (c[i][j] == 'S') { sh = i; sw = j; }
		}
	}
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < 1000; j++) {
			for (int k = 0; k < 1000; k++)
				d[j][k] = 500000;
		}
	
		d[sh][sw] = 0;
		judge(sh, sw, i);
		sh = gh; sw = gw;
}
	cout << ans << endl;

 	return 0;
}

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]])
			{
				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;
}