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 <cstring>
#include <cstdlib>
#include <queue>
using namespace std;

typedef pair<int, int> P;
typedef queue<P> Q;
const int INF = 10000000;

int main() {
  char buf[1001];
  char map[1000][1000];
  int d[1000][1000];
  int h, w, n;
  int sx, sy;
  int x, y;
  int nx, ny;
  int dx[4] = {0, 1, 0, -1};
  int dy[4] = {1, 0, -1, 0};
  int count;
  bool flg;
  Q q;

  cin >> h >> w >> n;
  for (int i=0; i<h; i++) {
    cin >> buf;
    memcpy(map[i], buf, w);
  }

  flg = false;
  for (int i=0; i<h; i++) {
    for (int j=0; j<w; j++) {
      if (map[i][j] == 'S') {
        sx = j;
        sy = i;
        flg = true;
        break;
      }
    }
    if (flg) break;
  }

  count = 0;
  for (int i=1; i<=n; i++) {
    for (int j=0; j<h; j++) {
      for (int k=0; k<w; k++) {
        d[j][k] = INF;
      }
    }
    q.push(P(sx, sy));
    d[sy][sx] = 0;
    while (q.size()) {
      P p = q.front();
      q.pop();
      x = p.first;
      y = p.second;
      if (map[y][x] == '0'+i) {
        count += d[y][x];
        while(!q.empty()) q.pop();
        sx = x;
        sy = y;
        break;
      }
      for (int j=0; j<4; j++) {
        nx = x + dx[j];
        ny = y + dy[j];
        if (nx>=0 && nx<=w && ny>=0 && ny<=h && map[ny][nx]!='X' && d[ny][nx]==INF) {
          d[ny][nx] = d[y][x] + 1;
          q.push(P(nx, ny));
        }
      }
    }
  }
  cout << count << endl;
  return 0;
}

C++: #include<iostream>
#include<stdio.h>
#include<queue>

using namespace std;
#define INF 1000000
typedef pair<int, int> P;

int d[1001][1001];
char map[1001][1001];
int dx[4] = {1,0,-1,0}, dy[4] = {0,-1,0,1};
int H, W, N;
int si, sj;
int gi, gj;
int sum = 0;

void bfs(P start, int goal){
    for(int i=0; i<H; i++){
        for(int j=0; j<W; j++){
            d[i][j] = INF;
            if(map[i][j]==goal+'0'){
                gi = i;
                gj = j;
            }
        }
    }

    d[start.first][start.second] = 0;
    queue<P> que;
    que.push(start);
    while(!que.empty()){
        P p = que.front();
        que.pop();
        if(p.first==gi && p.second==gj) break;
        int ni, nj;

        for(int i=0; i<4; i++){
            ni = p.first + dx[i];
            nj = p.second + dy[i];

            if(0<=ni && ni<H && 0<=nj && nj<W && map[ni][nj]!='X' && d[ni][nj]==INF){
                que.push(P(ni,nj));
                d[ni][nj] = d[p.first][p.second] + 1;
            }
        }
    }

    sum += d[gi][gj];

    if(goal!=N) bfs(P(gi,gj),goal+1);

}

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;
            }
        }
    }

    bfs(P(si,sj),1);
    printf("%d\n", sum);
    return 0;
}

C++: #include<cstdio>
#include<iostream>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<algorithm>
#include<string>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<sstream>
#include<stack>
#include<functional>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int INF=0x3f3f3f3f;
const int MAX_N = 10;
const int MAX_H = 1005;
const int dx[] = {0, 0, -1, 1};
const int dy[] = {1, -1, 0, 0};
struct T{
    int x,y;
};//坐?
char G[MAX_H][MAX_H];
T aim[MAX_N];
int vis[MAX_H][MAX_H]; // ???数
int H, W, N;
T s, t; //起点，?点

int bfs(){
    for(int i = 0; i < H; i++)
        for(int j = 0; j < W; j++)
            vis[i][j] = -1;
    queue<T> q;
    q.push(s);
    vis[s.x][s.y] = 0;
    while(!q.empty()){
        T cur = q.front();
        q.pop();
        if(cur.x == t.x && cur.y == t.y)break;
        for(int i = 0; i < 4; i++){
            T nxt;
            nxt.x = cur.x + dx[i];
            nxt.y = cur.y + dy[i];
            if(nxt.x >= 0 && nxt.x < H && nxt.y >= 0 && nxt.y < W && vis[nxt.x][nxt.y] == -1 && G[nxt.x][nxt.y] != 'X'){
                q.push(nxt);
                vis[nxt.x][nxt.y] = vis[cur.x][cur.y] + 1;
            }
        }
    }
    return vis[t.x][t.y];
}

void solve(){
    int ans = 0;
	for(int i = 0; i < N; i++){
        t = aim[i]; //?个?酪??点
        ans += bfs();
        s = t; //?次?点??下次起点
        G[s.x][s.y] = '.';
	}
	cout << ans << endl;
}
int main()
{
	#ifdef LOCAL
		freopen("in.txt","r",stdin);
	//	freopen("out.txt","w",stdout);
	#endif
	//ios::sync_with_stdio(false);
	cin >> H >> W >> N;
	int p = 0;
	for(int i = 0; i < H; i++){
        scanf("%s", G[i]);
        for(int j = 0; j < W; j++){
            if(G[i][j] == 'S'){
                s.x = i;s.y =j;
                G[i][j] = '.';
            }
            else if(G[i][j] <= '9' && G[i][j] >= 0){
                int num = G[i][j] - '0' - 1;
                aim[num].x = i;aim[num].y = j;
            }
        }
	}
	solve();
	return 0;
}

C++: #include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
#define MAXN 1005
#define inside(x,y) (x>0&&y>0&&x<=h&&y<=w)
#define encode(x,y) ((x-1)*w+y)
#define decodex(s) ((s-1)/w+1)
#define decodey(s) ((s-1)%w+1)
#define success(x,y) (x==gx&&y==gy)
const int dir[4][2]={{-1,0},{0,1},{1,0},{0,-1}};
int w,h,n;
char map[MAXN][MAXN];
int che[15][2];
int step[MAXN][MAXN];
int BFS(int sx,int sy,int gx,int gy)
{
	memset(step,0,sizeof step);
	step[sx][sy]=1;
	queue<int>Q;
	Q.push(encode(sx,sy));
	int s,x,y,tx,ty;
	while(!Q.empty())
	{
		s=Q.front();
		Q.pop();
		x=decodex(s);
		y=decodey(s);
		for(int d=0;d<4;d++)
		{
			tx=x+dir[d][0];
			ty=y+dir[d][1];
			if(!inside(tx,ty)||map[tx][ty]=='X'||step[tx][ty])
				continue;
			if(success(tx,ty))
				return step[x][y];
			step[tx][ty]=step[x][y]+1;
			Q.push(encode(tx,ty));
		}
	}
	return 0x7FFFFFFF;
}
int main()
{
	int sx,sy,gx,gy;
	scanf("%d%d%d",&h,&w,&n);
	for(int i=1;i<=h;i++)
	{
		scanf("%s",map[i]+1);
		for(int j=1;j<=w;j++)
		{
			if(map[i][j]>='0'&&map[i][j]<='9')
				che[map[i][j]-'0'][0]=i,
				che[map[i][j]-'0'][1]=j;
			if(map[i][j]=='S')
				sx=i,sy=j;
		}
	}
	int ans=0;
	for(int i=1;i<=n;i++)
	{
		gx=che[i][0];
		gy=che[i][1];
		ans+=BFS(sx,sy,gx,gy);
		sx=gx;
		sy=gy;
	}
	printf("%d\n",ans);
	return 0;
}