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<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define SC(x) scanf("%d",&x);
#define pr(x)  cout << x << endl;
#define mem(arr,v) memset(arr,v,sizeof arr);
#define bug(x) cout << "#x = " << x <<endl;
const int inf = 0x3f3f3f3f;
const int maxn = 1010;
typedef long long ll;
using namespace std;
char Mz[maxn][maxn],c;
bool vis[maxn][maxn];
int dir[4][2] = {1,0,-1,0,0,1,0,-1};
int M,N,C;
int px[10],py[10];
struct node {
	int x,y,step;
};

int bfs(int des,int sx,int sy) {
	mem(vis,0);
	vis[sx][sy] = 1;
	node nod = {sx,sy,0};
	queue<node> q;
	q.push(nod);

	while(!q.empty()) {
		nod =  q.front();
		q.pop();
		
		int x = nod.x, y = nod.y;
		int step =  nod.step;
		
		if(Mz[x][y] == des + '0')
			return step;
		for(int i =0 ; i < 4 ; i++) {
			int dx = x + dir[i][0];
			int dy = y + dir[i][1];
			if(Mz[dx][dy] == 'X' || Mz[dx][dy] == -1 || vis[dx][dy])	continue;
			nod = {dx,dy,step + 1};
			q.push(nod);
			vis[dx][dy] = 1;
		}
	}
}

int main() {
//	freopen("in.txt","r",stdin);
	cin >> N >> M >> C;
	mem(Mz,-1)
	mem(px,0)  mem(py,0)

	for(int i = 1 ; i <= N ; i++)
		for(int j = 1; j <= M ; j++) {
			cin >> c;
			Mz[i][j] = c;
			if(c == '.' || c == 'X')	continue;
			if(c == 'S') px[0] = i, py[0] = j;
			else
				px[c - '0'] = i , py[c - '0'] = j;
		}
	int res = 0;
	for(int i = 0 ; i < C ; i++) {
		if(px[i] && py[i]) {
//				dfs(i + 1,px[i],py[i],0);
			res += bfs(i + 1,px[i],py[i]);
		}
	}
	printf("%d\n",res);
}

C++: #include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<set>
#include<utility>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
using namespace std;
#define MP make_pair
#define PB push_back
#define F_d first
#define S_d second
#define LARGE 100000000
#define MOD 100000
#define LL long long

int H, W, N, ITR = 0, ans = 0;
string grid[1009];
int cost[1009][1009];
pair<int, int> NUM[15], st, go;//S123456789
queue<pair<int, int>>Q;

void solve(pair<int, int> now) {
	int i = now.F_d, j = now.S_d;
	if (i + 1 < H && grid[i + 1][j] != 'X' && cost[i + 1][j] > cost[i][j] + 1) {
		cost[i + 1][j] = cost[i][j] + 1; Q.push(MP(i + 1, j));
	}
	if (i > 0 && grid[i - 1][j] != 'X' && cost[i - 1][j] > cost[i][j] + 1) {
		cost[i - 1][j] = cost[i][j] + 1; Q.push(MP(i - 1, j));
	}
	if (j + 1 < W && grid[i][j + 1] != 'X' && cost[i][j + 1] > cost[i][j] + 1) {
		cost[i][j + 1] = cost[i][j] + 1; Q.push(MP(i, j + 1));
	}
	if (j > 0 && grid[i][j - 1] != 'X' && cost[i][j - 1] > cost[i][j] + 1) {
		cost[i][j - 1] = cost[i][j] + 1; Q.push(MP(i, j - 1));
	}
	return;
}


int main() {
	cin >> H >> W >> N;
	for (int i = 0; i < H; i++) {
		cin >> grid[i];
		for (int j = 0; j < W; j++) {
			cost[i][j] = LARGE;
			if (grid[i][j] == 'X') ;
			else if (grid[i][j] == 'S') NUM[0] = MP(i, j);
			else if (grid[i][j] != '.') NUM[grid[i][j] - '0'] = MP(i, j);
		}
	}

	for (int i = 0; i < N; i++) {
		st = NUM[i]; go = NUM[i + 1];
		cost[st.F_d][st.S_d] = 0;
		Q.push(st);
		while (!Q.empty()) {
			pair<int, int>now = Q.front();
			solve(now);
			Q.pop();
		}
		ans += cost[go.F_d][go.S_d];
		for (int i = 0; i < H; i++) {
			for (int j = 0; j < W; j++) cost[i][j] = LARGE;
		}
	}
	cout << ans << endl;

	return 0;
}

//チーズ
/*
int H, W, N, ans, tag, si, sj;
char MAP[1009][1009];
int dp[1009][1009];

bool inmap(int i, int j) {
return ((i >= 0 && i <= H - 1) && (j >= 0 && j <= W - 1));
}
bool pass(int i, int j) {
return (MAP[i][j] != 'X');
}

int DFS(int i, int j) {
if (dp[i][j] != LARGE)return dp[i][j];
if (MAP[i][j] - '0' == tag) {
si = i; sj = j;
return 0;
}

if (inmap(i + 1, j) && pass(i + 1, j)) dp[i][j] = min(dp[i][j], DFS(i + 1, j) + 1);
if (inmap(i - 1, j) && pass(i - 1, j)) dp[i][j] = min(dp[i][j], DFS(i - 1, j) + 1);
if (inmap(i, j + 1) && pass(i, j + 1)) dp[i][j] = min(dp[i][j], DFS(i, j + 1) + 1);
if (inmap(i, j - 1) && pass(i, j - 1)) dp[i][j] = min(dp[i][j], DFS(i, j - 1) + 1);
cout << i << " " << j << " " << dp[i][j] << endl;
return dp[i][j];
}

int main() {
cin >> H >> W >> N;
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
cin >> MAP[i][j];
if (MAP[i][j] == 'S') {
si = i; sj = j;
}
}
}

for (int i = 1; i <= N; i++) {
cout << i << " " << si << " " << sj << endl << endl;
for (int j = 0; j < H; j++) {
for (int k = 0; k < W; k++) {
dp[j][k] = LARGE;
}
}
tag = i;
ans += DFS(si, sj);

}

cout << ans << endl;
return 0;
}
*/

C++: #include <cstdio>
#include <queue>
#define min(x,y) ((x)<(y)?(x):(y))
#define INFI 65535

using namespace std;
typedef pair<int, int> P;

int Strength = 1;
int Maps[1010][1010];
int dist[1010][1010];
int H, W, N;
int hor[] = {1,0,-1,0};
int ver[] = {0,-1,0,1};
int ans;


void clear();
void show();
P bfs(int cheese,P n);

int main(void) {
    scanf("%d %d %d\n", &H, &W, &N);
    P s,e;
    for (int i = 0; i<H; i++) {
        for (int j = 0; j<W; j++) {
            Maps[i][j] = getchar();
            if (Maps[i][j]=='S') {s.first = i; s.second = j;}
            if (Maps[i][j]=='0'+N) {e.first = i; e.second = j;}
        }
        getchar();
    }

    
    P tmp;
    tmp.first = s.first; tmp.second = s.second;
    
    for (int i = 1; i<=N; i++) {
        clear();
        tmp = bfs(i, tmp);
    }
    
    
    
    printf("%d\n", ans);
    return 0;
}

P bfs(int cheese,P n) {
    P end;
    queue<P> que;
    que.push(n);
    dist[n.first][n.second] = 0;
    
    while (que.size()) {
        P top = que.front();
        
        que.pop();
        for (int i = 0; i<4; i++) {
            int nx = top.first+ver[i], ny = top.second+hor[i];
            if (nx>=0 && nx<H && ny>=0 && ny<W && dist[nx][ny]==INFI) {
                if (Maps[nx][ny]=='.' || (isdigit(Maps[nx][ny]) && cheese!=Maps[nx][ny]-'0'))  {
                    que.push(P(nx,ny));
                    dist[nx][ny] = min(dist[nx][ny], dist[top.first][top.second]+1);
                } else if (isdigit(Maps[nx][ny]) && cheese==Maps[nx][ny]-'0') {
                    que.push(P(nx,ny));
                    dist[nx][ny] = min(dist[nx][ny], dist[top.first][top.second]+1);
                    end.first = nx; end.second = ny;
                    break;
                }
            }
        }
    }
    ans += dist[end.first][end.second];
    return end;
}

void clear() {
    for (int i = 0; i<H; i++)
        for (int j = 0; j<W; j++)
            dist[i][j] = INFI;
}