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<cctype>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<cassert>
#include<cctype>
#include<cstring>
#include<utility>
#include<cmath>
const int inf=0x7fffffff;
typedef long long int ll;
using namespace std;
const bool test=0;
int n,w,h;
int const N=1000+10;
char A[N][N];
char V[N][N];
char s[N];
int _h,_w;
int mov[2][4]={
	0,0,-1,1,
	-1,1,0,0
};
void show(){
	if(test){
		for(int i=1;i<=_h;i++){
			for(int j=1;j<=_w;j++){
				printf("%2d",A[i][j]);
			}
			printf("\n");
		}

	}
}
const int H=0,W=1;
struct point{
	int h;
	int w;
	int cnt;
	point(int h=1,int w=1,int cnt=inf):h(h),w(w),cnt(cnt){}
};
int cor(char x,int i,int j){
	switch(x){
		case 'S':
			h=i;
			w=j;
			return 0;
			break;
		case 'X':
			return -1;
		case '.':
			return 0;
		default:
			return x-'0';
	}
}
int search(int goal){
	memset(V,0,sizeof(V));
	int cnt=0;
	queue<point> q;
	q.push(point(h,w,cnt));
	point p;
	if(test){cout<<"root"<<cnt<<' '<<h<<' '<<w<<endl;
		show();
	}
	while(q.size()){
		p=q.front();
		q.pop();
		h=p.h;
		w=p.w;
		cnt=p.cnt;
		if(V[h][w]!=0)continue;
		if(A[h][w]==goal){
			return cnt;
		}
		if(test)cout<<"q.size "<<q.size()<<" cnt "<<cnt<<' '<<h<<' '<<w<<' '<<(int)V[h][w]<<" goal "<<goal<<endl;
		for(int c=0;c<4;c++){
			int tmph=h+mov[H][c];
			int tmpw=w+mov[W][c];
			if(!V[tmph][tmpw]&&A[h][w]!=-1)q.push(point(tmph,tmpw,cnt+1));
		}
		V[h][w]=1;
	}
	assert(q.size());
}
void solve(){
	int sum=0;
	for(int i=1;i<=n;i++){
		sum+=search(i);
	}
	cout<<sum<<endl;
}
int main()
{
	scanf("%d%d%d", &h,&w,&n);
	_h=h;
	_w=w;
	memset(A,-1,sizeof(A));
	for(int i=1;i<=_h;i++){
		scanf("%s",s);
		for(int j=1;j<=_w;j++){
			A[i][j]=cor(s[j-1],i,j);
		}
	}
	show();
	solve();
	return 0;
}
////aoj0558.cc
////generated automatically at Fri Sep  9 18:27:24 2016
////by xsthunder
/

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

int h,w,n;
char map[1000][1000];
struct P{
  int t, i,j;
  P(){t=0;i=0;j=0;};
  P(int time,int x, int y){t=time;i=x;j=y;};
};
int cal(int a, int b){
  char start = a==0?'S':'0'+a;
  bool flags[1000][1000];
  int si,sj;
  for( int i=0;i<h;i++ )
    for( int j=0;j<w;j++ ){
      flags[i][j] = false;
      if( map[i][j] == start ){
	si=i; sj=j;
      }
    }

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

  queue<P> q;
  q.push(P(0, si, sj));
  while( !q.empty() ){
    P p = q.front(); q.pop();
    if( p.i < 0 || p.j < 0 ) continue;
    if( p.i >=h || p.j>=w )  continue;

    //    if( flags[p.i][p.j] ) continue;
    flags[p.i][p.j] = true;

    if( map[p.i][p.j] == '0' + b )
      return p.t;
    if( map[p.i][p.j] == 'X' )
      continue;

    p.t++;
    for( int d=0;d<4;d++ ){
      int ni = p.i+dx[d], nj=p.j+dy[d];
      if( flags[ni][nj] ) continue;
      q.push(P(p.t, ni, nj) );
    }
  }

  return -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];

  int time=0, r;
  for( int i=0;i<n;i++ ){
    r = cal( i, i+1);
    time += r;
    //    cout << i << " => " << (i+1) << "\t | " << r << endl;
  }
  cout << time << endl;

  return 0;
}

C++: 
#include<iostream>
#include<cstdio>
#include<deque>
#include<algorithm>

using namespace std;

const int maxn=1e3+5;
const int inf=0x3f3f3f3f;

typedef pair<int,int>P;

int h,w,n,sx,sy,book[maxn][maxn],goal[10],Next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
char s[maxn][maxn];

int judge(int row,int col)
{
    if(row>=0&&row<h&&col>=0&&col<w){
        return 1;
    }
    return 0;
}

int bfs()
{
    int res=0;
    deque<P>q;
    for(int ci=0;ci<n;ci++){
        fill(book[0],book[0]+maxn*maxn,inf);
        q.push_back(P(sx,sy));
        book[sx][sy]=0;
        while(!q.empty()){
            int x=q.front().first;
            int y=q.front().second;
            q.pop_front();
            if((int)s[x][y]==49+ci){
                goal[ci]=book[x][y];
                sx=x;
                sy=y;
                break;
            }
            for(int i=0;i<4;i++){
                int nx=x+Next[i][0];
                int ny=y+Next[i][1];
                if(judge(nx,ny)&&s[nx][ny]!='X'&&book[nx][ny]==inf){
                    q.push_back(P(nx,ny));
                    book[nx][ny]=book[x][y]+1;
                }
            }
        }
        q.clear();
        res+=goal[ci];
    }
    return res;
}

int main()
{
    cin>>h>>w>>n;
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            cin>>s[i][j];
            if(s[i][j]=='S'){
                sx=i;
                sy=j;
            }
        }
    }
    int res=bfs();
    cout<<res<<endl;
    return 0;
}

C++: #include<stdio.h>
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
typedef pair<int, int> P;
int n, m, ci,sum1,book[1010][1010];
char Map[1010][1010];
queue<P>q;
struct node {
	int x;
	int y;
}node[10];
void bfs(int sx, int sy, int ex, int ey)
{
	sum1 = 0;
	int dx[] = { 0,0,1,-1 };
	int dy[] = { 1,-1,0,0 };
	while (!q.empty())
		q.pop();
	q.push(P(sx, sy));
	book[sx][sy] = 1;
	while (!q.empty())
	{
		int l = q.size();
		sum1++;
		while (l)
		{
			l--;
			P p = q.front(); q.pop();
			for (int i = 0; i < 4; i++)
			{
				int nx = p.first + dx[i];
				int ny = p.second + dy[i];
				if (nx < n&&nx >= 0 && ny >= 0 && ny < m)
				{
					if (ny == ey&&nx == ex)
						return;
					else if (Map[nx][ny] != 'X'&&!book[nx][ny])
					{
						book[nx][ny] = 1;
						q.push(P(nx, ny));
					}
				}
			}
		}
	}
}
int main()
{
	freopen("C:\\Users\\国民党\\Desktop\\text.txt", "r", stdin);
	int sum = 0;
	scanf("%d%d%d", &n, &m, &ci);
	for (int i = 0; i < n; i++)
	{
		scanf("%s", &Map[i]);
		for (int j = 0; j < m; j++)
		{
			if (Map[i][j] == 'S')
			{
				node[0].x = i;
				node[0].y = j;
			}
			else if (Map[i][j] <= '9'&&Map[i][j] >= '1')
			{
				node[Map[i][j] - 48].x = i;
				node[Map[i][j] - 48].y = j;
			}
		}
	}
	if (ci == 0)
		printf("0\n");
	else
	{
		for (int i = 0; i < ci; i++)
		{
			memset(book, 0, sizeof(book));
			bfs(node[i].x, node[i].y, node[i + 1].x, node[i + 1].y);
			sum += sum1;
		}
		printf("%d\n", sum);
	}
	return 0;
}