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<deque>
#include<queue>
#include<cstring>

#define INF 10000000

using namespace std;

char ban[1001][1001];
int d[1001][1001];			//en_ÜÅÌÅZ£


class mouse
{
	public:
	mouse(int xx, int yy, int p, int c){
		x = xx;
		y = yy;
		pow = p;
		cont = c;
	}
	int x, y;		//»ÝÀW
	int pow;		//ÌÍ
	int cont;		//è
	
};


int h, w, c;

int main()
{
	int st_y, st_x;
	int g_x, g_y;
	int vec[2] = {-1,1};
	
	cin >> h >> w >> c;
	
	for(int i = 0; i < h; i++){
		for(int j = 0; j < w; j++){
			cin >> ban[i][j];
			if(ban[i][j] == 'S'){
				st_y = i;
				st_x = j;
			}
			if(ban[i][j]-48 == c){
				g_x = j;
				g_y = i;
			}
			d[i][j] = INF;
		}
	}
	
	queue<mouse> Q;
	
	Q.push(mouse(st_x, st_y, 1, 0));
	d[st_x][st_y] = 0;
	
	int cont = 1;
	int tesu = 0;
	
	while(1)
	{
		for(int i = 0; i < h; i++){
			for(int j = 0; j < w; j++){
				d[i][j] = INF;
			}
		}
		
		while(1)
		{
			mouse temp = Q.front();
			Q.pop();
			
			if(ban[temp.y][temp.x]-48 == cont){
				tesu += d[temp.y][temp.x];
//				printf("±±ÜÅÌèF%d\n",d[temp.y][temp.x]);
						
				while(!Q.empty()){
					Q.pop();
				}
				Q.push(mouse(temp.x, temp.y, 0, 0));
				break;
			}
			
			//óÔ¶¬
			for(int i = 0; i < 2; i++){
				if(temp.x + vec[i] > -1 && temp.x + vec[i] < w && d[temp.y][temp.x+vec[i]] == INF && ban[temp.y][temp.x+vec[i]] != 'X'){
					Q.push(mouse(temp.x+vec[i],temp.y,temp.pow,temp.cont+1));
					d[temp.y][temp.x+vec[i]] = temp.cont+1;
					
//					printf("x:%d y:%d cont:%d\n",temp.x+vec[i],temp.y,temp.cont+1);
				}
				if(temp.y + vec[i] > -1 && temp.y + vec[i] < h && d[temp.y+vec[i]][temp.x] == INF && ban[temp.y+vec[i]][temp.x] != 'X'){
					Q.push(mouse(temp.x,temp.y+vec[i],temp.pow,temp.cont+1));
					d[temp.y+vec[i]][temp.x] = temp.cont+1;
					
//					printf("x:%d y:%d cont:%d\n",temp.x,temp.y+vec[i],temp.cont+1);
				}
			}
		}
		cont++;
		
		if(cont-1 == c){
			break;
		}

	}
	
	cout << tesu << endl;
}

C++: /*
 * AOJ 0558: Cheese
 * ?¢???????m*n???????????????????????????1???N??¨???N?????\??????????¢??????????????±????????????????1???N???????????????
 * ?±???????BFS???Queue??????Dijkstra???
 * ????????????S????????????1???N????????????????????\??¨BFS?±?N?¬???????????????´??????????????????
 */

#include <cstdio>
#include <iostream>
#include <queue>

using namespace std;

typedef pair<int, int> pii;

int m, n, N;
char mat[1002][1002];
int d[1002][1002];
int sx[10], sy[10];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
int ans;

int bfs(int sx, int sy, int tx, int ty) {
  memset(d, -1, sizeof(d));
  d[sx][sy] = 0;
  queue<pii> q;
  q.push(make_pair(sx, sy));
  int x, y, xx, yy;
  while (!q.empty()) {
    pii cur = q.front();
    q.pop();
    x = cur.first;
    y = cur.second;
    for (int i = 0; i < 4; ++i) {
      xx = x + dx[i];
      yy = y + dy[i];
      if (xx >= 0 && xx < m && yy >= 0 && yy < n && mat[xx][yy] != 'X' && d[xx][yy] == -1) {
        d[xx][yy] = d[x][y] + 1;
        if (xx == tx && yy == ty) {
          return d[xx][yy];
        }
        q.push(make_pair(xx, yy));
      }
    }
  }

}

void solve() {
  ans = 0;
  for (int i = 0; i < m; ++i) {
    cin >> mat[i];
    for (int j = 0; j < n; ++j) {
      if (mat[i][j] == 'S') {
        sx[0] = i;
        sy[0] = j;
      } else if (mat[i][j] >= '1' && mat[i][j] <= '9') {
        int t = mat[i][j] - '0';
        sx[t] = i;
        sy[t] = j;
      }
    }
  }
  for (int i = 1; i <= N; ++i) {
    int tmp = bfs(sx[i - 1], sy[i - 1], sx[i], sy[i]);
    ans += tmp;
  }
}

int main() {
  cin >> m >> n >> N;
  solve();
  cout << ans << endl;
  return 0;
}

C++: #include <bits/stdc++.h>
#define GET_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,NAME,...) NAME
#define pr(...) cerr<< GET_MACRO(__VA_ARGS__,pr8,pr7,pr6,pr5,pr4,pr3,pr2,pr1)(__VA_ARGS__) <<endl
#define pr1(a) (#a)<<"="<<(a)<<" "
#define pr2(a,b) pr1(a)<<pr1(b)
#define pr3(a,b,c) pr1(a)<<pr2(b,c)
#define pr4(a,b,c,d) pr1(a)<<pr3(b,c,d)
#define pr5(a,b,c,d,e) pr1(a)<<pr4(b,c,d,e)
#define pr6(a,b,c,d,e,f) pr1(a)<<pr5(b,c,d,e,f)
#define pr7(a,b,c,d,e,f,g) pr1(a)<<pr6(b,c,d,e,f,g)
#define pr8(a,b,c,d,e,f,g,h) pr1(a)<<pr7(b,c,d,e,f,g,h)
#define prArr(a) {cerr<<(#a)<<"={";int i=0;for(auto t:(a))cerr<<(i++?", ":"")<<t;cerr<<"}"<<endl;}
using namespace std;
using Int = long long;
using _int = int;
using ll = long long;
using Double = long double;
const Int INF = (1LL<<60)+1e9; // ~ 1.15 * 1e18
const Int mod = (1e9)+7;
const Double EPS = 1e-8;
const Double PI = 6.0 * asin((Double)0.5);
using P = pair<Int,Int>;
template<class T> T Max(T &a,T b){return a=max(a,b);}
template<class T> T Min(T &a,T b){return a=min(a,b);}
template<class T1, class T2> ostream& operator<<(ostream& o,pair<T1,T2> p){return o<<"("<<p.first<<","<<p.second<<")";}
template<class T1, class T2, class T3> ostream& operator<<(ostream& o,tuple<T1,T2,T3> t){
  return o<<"("<<get<0>(t)<<","<<get<1>(t)<<","<<get<2>(t)<<")";}
template<class T1, class T2> istream& operator>>(istream& i,pair<T1,T2> &p){return i>>p.first>>p.second;}
template<class T> ostream& operator<<(ostream& o,vector<T> a){Int i=0;for(T t:a)o<<(i++?" ":"")<<t;return o;}
template<class T> istream& operator>>(istream& i,vector<T> &a){for(T &t:a)i>>t;return i;}
//INSERT ABOVE HERE

int v[2000001];
int head = 0, tail = 0;
int front(){return v[head];}
void pop(){head++;}
void push(int a){v[tail] = a, tail++;}
bool empty(){return head == tail;}
bool size(){return tail - head;}
void initQueue(){head = tail = 0;}

int H, W, N;
string mp[1001];
int dist[1001][1001];

int bfs(int sy, int sx, int gy, int gx){
  initQueue();
  for(int i=0;i<H;i++)
    for(int j=0;j<W;j++) dist[i][j] = 1e9;
  
  push(sy * W + sx);
  dist[sy][sx] = 0;

  while(!empty()){
    int num = front(); pop();
    int y = num / W;
    int x = num % W;
    int cost = dist[y][x];
    if(y == gy && x == gx) return cost;
    int dy[4] = {-1, 0, 1, 0};
    int dx[4] = {0, 1, 0, -1};
    for(int i=0;i<4;i++){
      int ny = y + dy[i];
      int nx = x + dx[i];
      if(ny < 0 || nx < 0 || ny >= H || nx >= W) continue;
      if(mp[ny][nx] == 'X' || dist[ny][nx] != 1e9) continue;
      push(ny * W + nx);
      dist[ny][nx] = cost + 1;
    }
  }
  assert(0);
}

signed main(){
  srand((unsigned)time(NULL));
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(12);

  cin>>H>>W>>N;
  for(int i=0;i<H;i++) cin>>mp[i];

  int sy[10], sx[10];
  for(int i=0;i<H;i++)
    for(int j=0;j<W;j++){
      if(mp[i][j] == 'S') sy[0] = i, sx[0] = j;
      if('0' <= mp[i][j] && mp[i][j] <= '9') sy[mp[i][j] - '0'] = i, sx[mp[i][j] - '0'] = j;
    }

  int ans = 0;
  for(int i=0;i<N;i++){
    ans += bfs(sy[i], sx[i], sy[i+1], sx[i+1]);
  }

  cout<<ans<<endl;

  return 0;
}