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 <queue>
using namespace std;

int h,w,n;
const int MAX_N=1005;
char map[MAX_N][MAX_N];
int visit[MAX_N][MAX_N];
struct point{
    int x,y;
    int step;
    point(){
        x=0; y=0; step=0;
    }
    point(int xx, int yy, int ss){
        x=xx;
        y=yy;
        step=ss;
    }
};
struct point p[16];

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

int ok(int x, int y){
    if(x>=0 && x<h && y>=0 && y<w) return 1;
    return 0;
}

int bfs(int next){
    for(int i=0; i<MAX_N; i++){
        for(int j=0; j<MAX_N；j++){
            visit[i][j]==0;
        }
    }
    int nextcheese = next +1; 
    
    queue<point> q;
    point cur(p[next].x, p[next].y,0);
    q.push(cur);
    while(q.size()){
        cur = q.front(); q.pop(); 
        int x=cur.x, y=cur.y;
        int nx, ny;
        for(int i=0; i<4; i++){
            nx = x+dx[i]; ny=y+dy[i];
            if(ok(nx, ny)){
                if((map[nx][ny]-'0')==nextcheese) return ++cur.step;
                if((map[nx][ny]=='.')&&visit[nx][ny]==0){
                    q.push(point(nx, ny, cur.step+1));
                    visit[nx][ny]=1;
                }
            }
        }
    }
}

void solve(){
    cin>>h>>w>>n;
    for(int i=0; i<h; i++){
        for(int j=0; j<w; j++){
            cin>>map[i][j];
        }
    }
    for(int i=0; i<h; i++){
        for(int j=0; j<w; j++){
            char ch=map[i][j];
            switch(ch){
                case '.': break;
                case 'X': break;
                case 'S': p[0].x = i; p[0].y = j; map[i][j]='.';break;
                default:
                int t=(ch-'0');
                p[t].x = i; p[t].y = j;
            }
           /* if(map[i][j]=='S'){
                p[0].x=i; p[0].y = j;
                map[i][j]='.';
            }
            else if(isdigit(map[i][j])){
                int index=map[i][j]-'0';
                p[index].x=i; p[index].y=j;
            }*/
        }
    }
    int step=0;
    for(int i=0; i<n; i++){
        step+=bfs(i);
    }
    printf("%d\n", step);
}


int main(){
    solve();
}

C++: //bfs
#include<vector>
#include<list>
#include<deque>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cmath>
#include<iostream>
#include<limits>
#include<utility>

#define c11
#ifdef c11
#include<unordered_set>
#include<unordered_map>
#endif

using namespace std;
typedef long long ll;
#define ull unsigned long long
#define PI acos(-1.0)
#define eps 1e-12
#define cls(x) memset(x,0,sizeof(x))
#define forn(i, n) for(int i = 0; i < (int) n; ++i)
#define for1(i, n) for(int i = 1; i <= (int) n; ++i)
#define fore(i, l, r) for(int i = (int) l; i <= (int) r; ++i)
#define rforn(i, n) for(int i = (int) n - 1; i>= 0; ++i)

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

const int INF = 0x3f3f3f3f;
const int SZ = 1005;

int h, w, n;

char maze[SZ][SZ];
int dist[SZ][SZ];
int cx, cy;

int bfs(char target) {
  forn(i, h) {
    forn(j, w) {
      dist[i][j] = INF;
    }
  }
  dist[cx][cy] = 0;
  queue<pair<int,int>> q;
  q.push({cx, cy});
  while(!q.empty()) {
    auto cur = q.front(); q.pop();
    if(maze[cur.first][cur.second] == target) {
      cx = cur.first;
      cy = cur.second;
      return dist[cx][cy];
    }
    for(int d = 0; d < 4; ++d) {
      int nx = cur.first + dx[d];
      int ny = cur.second + dy[d];
      if(0 <= nx && nx < h && 0 <= ny && ny < w && maze[nx][ny] != 'X' && dist[nx][ny] == INF){
        q.push({nx, ny});
        dist[nx][ny] = dist[cur.first][cur.second] + 1;
      }
    }
  }
  return -1;
}

int main() {
  cin >> h >> w >> n;
  forn(i, h) {
    forn(j, w) {
      cin >> maze[i][j];
      if(maze[i][j] == 'S') {
        cx = i;
        cy = j;
      }
    }
  }
  int ret = 0;
  for1(t,n) {
    ret += bfs('0' + t);
  }
  cout << ret << endl;
	return 0;
}

C++: #include <iostream>
#include <vector>
#include <queue>
#include <algorithm>

#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define pb push_back
#define mp(a,b) make_pair(a,b)
#define all(a) a.begin(),a.end()
#define pii pair<int, int>
#define ll long long
using namespace std; 

#define MAX 10
#define SIZE 1000
#define INF 1<<30

int H, W, N;
char sec[SIZE][SIZE+1];
int move_cnt = INF;
int all_move_cnt = 0;
int dy[4] = {-1, 0, 1, 0};
int dx[4] = {0, 1, 0, -1};
int facy[10] = {};
int facx[10] = {};

struct state {
	int sy, sx, gy, gx, cnt;
	state() {}
	state(int _sy, int _sx, int _gy, int _gx, int _cnt) :
		sy(_sy), sx(_sx), gy(_gy), gx(_gx), cnt(_cnt) {}
};
queue<state> que;

void bfs()
{
	int **tsec = new int*[SIZE];
	rep(i,0,SIZE) tsec[i] = new int[SIZE+1];
	rep(i,0,H) rep(j,0,W) tsec[i][j] = (int)sec[i][j];
	//rep(i,0,H) { rep(j,0,W) cout << tsec[i][j] << " "; cout << endl;}

	while (!que.empty()) {
		state ts = que.front(); que.pop();
		//printf("sy=%d sx=%d gy=%d gx=%d cnt=%d\n",ts.sy,ts.sx,ts.gy,ts.gx,ts.cnt);
		if (ts.cnt > move_cnt) return;
		if (ts.sy == ts.gy && ts.sx == ts.gx) move_cnt = min(move_cnt, ts.cnt);
		tsec[ts.sy][ts.sx] = ts.cnt;

		rep(i, 0, 4) {
			int ny = ts.sy + dy[i];
			int nx = ts.sx + dx[i];
			if (ny < 0 || ny >= H) continue;
			if (nx < 0 || nx >= W) continue;
			if (sec[ny][nx] == 'X') continue;
			if (tsec[ny][nx] < ts.cnt) continue; 
			state ns(ny, nx, ts.gy, ts.gx, ts.cnt + 1);
			que.push(ns);
		}
	//rep(i,0,H) { rep(j,0,W) cout << tsec[i][j] << " "; cout << endl;}
	}

	rep(i,0,SIZE) delete[] tsec[i];
	delete[] tsec;
}

void solve()
{
	// rep(i,0,N+1) printf("%d y=%d x=%d\n",i,facy[i],facx[i]);

	rep(i,0,N) {
		move_cnt = INF;
		while(!que.empty()) que.pop();
		state s(facy[i], facx[i], facy[i+1], facx[i+1], 0);
		que.push(s);
		//printf("\n bfs start !! \n");
		bfs();
		all_move_cnt += move_cnt;
	}

	cout << all_move_cnt << endl;
}

void input()
{
	cin >> H >> W >> N;
	rep(i,0,H) { 
		rep(j,0,W) {
			cin >> sec[i][j];
			if (sec[i][j] == 'S') { facy[0] = i; facx[0] = j; }
			if (sec[i][j] >= 49 && 57 >= sec[i][j]) {
				facy[sec[i][j]-48] = i;
				facx[sec[i][j]-48] = j;
			}
		}
	}
	solve();
}

int main(void)
{
	input();
	
	return 0;
}