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<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
#include<algorithm>
#include<utility>
using namespace std;
const int INF=100000000;
char a[1005][1005];
int b[1005][1005];
int h,w,n;
int  sx,sy,gx,gy;
int xx[4]={0,0,1,-1};
int yy[4]={-1,1,0,0};
typedef pair<int,int> P;
 int jj;
int bfs()
{

    queue <P> que;
    for(int i=0;i<h;i++)
            for(int j=0;j<w;j++)
            b[i][j]=INF;
        que.push(P(sx,sy));
        b[sx][sy]=0;

        while(que.size())
        {
        P p=que.front();
        que.pop();
        if((a[p.first][p.second]-'0')==jj)//我居然用 int型的JJ去剪'0'  ??我特?太智障了。。。！！
        {
            gx=p.first;             //数字?始  ?点?? 起点
            gy=p.second;
            sx=gx;
            sy=gy;
            a[gx][gy]='.';
            //return b[gx][gy];
            break;
        }
        for(int i=0;i<4;i++)
        {
            int nx=p.first+xx[i];
            int ny=p.second+yy[i];
            if(nx>=0&&nx<h&&ny>=0&&ny<w&&a[nx][ny]!='X'&&b[nx][ny]==INF)//?里  nx ny也没有 写上等于0的情况
            {
                que.push(P(nx,ny));
                //a[nx][ny]='#';
                b[nx][ny]=b[p.first][p.second]+1;
            }
        }

        }
return b[gx][gy];
}

int main()
{
    while(~scanf("%d%d%d",&h,&w,&n))
    {

        getchar();
        for(int i=0;i<h;i++)
        {
            for(int j=0;j<w;j++)
            {
                scanf("%c",&a[i][j]);
                if(a[i][j]=='S')
                {
                    sx=i;
                    sy=j;
                    a[i][j]='.';
                }
            }
            getchar();
        }
       /*
        for(int i=0;i<h;i++)
            for(int j=0;j<w;j++)
            b[i][j]=INF;
         //*/
         int res=0;
            for( jj=1;jj<=n;jj++)
            {
                int num = bfs();
                res+=num;
            }

        //int res=bfs();
        printf("%d\n",res);
        /*
        for(int i=0;i<h;i++)
        {
            for(int j=0;j<w;j++)
            {
                printf("%c",a[i][j]);
            }
            printf("\n");
        }
        */
    }
    return 0;
}

C++: #include<bits/stdc++.h>
using namespace std;
#define ff first
#define fs second
typedef pair<int,int> P;
int n,m,k,i,j,kage[1001][1001],p,l;
int main(void)
{
	char cf[20]="123456789";
	char mp[1001][1001];
	int x[5]={1,0,-1,0},y[5]={0,1,0,-1};
	queue<P> qu;
	queue<int> q; 
	P pp;
	scanf("%d %d %d",&n,&m,&k);
	for(i=0;i<n;i++) scanf("%s",mp[i]);
	for(i=0;i<n;i++) for(j=0;j<m;j++) {
			kage[i][j]=0;
			if(mp[i][j]=='S') qu.push(P(i,j));
	}
	pp=qu.front();
	kage[pp.ff][pp.fs]=1;
	q.push(0);
	for(l=1;l<=k;l++){
		//printf("aa\n");
		while(qu.size()!=0){
			pp=qu.front();
			p=q.front();
			if(mp[pp.ff][pp.fs]==cf[l-1]) break;
			for(i=0;i<4;i++){
				if(pp.ff+y[i]<0||pp.ff+y[i]>=n||pp.fs+x[i]<0||pp.fs+x[i]>=m);
				else if(mp[pp.ff+y[i]][pp.fs+x[i]]!='X'&&kage[pp.ff+y[i]][pp.fs+x[i]]<l){
					qu.push(P(pp.ff+y[i],pp.fs+x[i]));
					q.push(p+1);
					kage[pp.ff+y[i]][pp.fs+x[i]]=l;
					//printf("p=%d %d %d\n",p,pp.ff+y[i],pp.fs+x[i]);
				}
			}
			qu.pop();
			q.pop();
		}
		while(qu.size()!=0&&q.size()!=0){
			qu.pop();
			q.pop();
		}
		//printf("A p=%d %d %d\n",p,pp.ff+y[i],pp.fs+x[i]);
		qu.push(P(pp.ff,pp.fs));
		q.push(p);
	}
	printf("%d\n",p);
	return 0;
}

C++: 
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;
const int maxn = 1e3 + 5;
const int dir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
int mp[maxn][maxn];
//bool vis[maxn][maxn];
int d[maxn][maxn];
struct point{
    int x,y;
};
int h,w,n;
 int dis = 0;
void bfs(point &p,int cnt)
{
   // memset(vis, 0, sizeof(vis));
    memset(d, 0, sizeof(d));
    queue<point> q;
    q.push(p);
    while (!q.empty()) {
        point t = q.front();q.pop();
        //vis[t.x][t.y] = true;
        if(mp[t.x][t.y] == cnt + 1) {dis += d[t.x][t.y];p.x = t.x,p.y = t.y;return ;}
        for (int i = 0; i < 4; i ++) {
            int tx = t.x + dir[i][0];
            int ty = t.y + dir[i][1];
            if (tx >= 0 && tx < h && ty >= 0 && ty < w && !d[tx][ty] && mp[tx][ty] != -1) {
                q.push({tx,ty});
                d[tx][ty] = 1 + d[t.x][t.y];
            }
        }
    }
}
int main()
{
    while (scanf("%d%d%d",&h,&w,&n) != EOF) {
        getchar();
        char ch;
        memset(mp, -1, sizeof(mp));
       // int sx,sy;
        point s;
        for (int i = 0; i < h; i ++) {
            for (int j = 0; j < w; j ++) {
                scanf("%c",&ch);
                if(ch == 'S') {s.x = i,s.y = j;mp[i][j] = 0;}
                else if(ch == '.') {mp[i][j] = 0;}
                else if(isdigit(ch)) {mp[i][j] = ch - '0';}
            }
            getchar();
        }
       
        dis = 0;
        for (int i = 0; i < n; i ++) {
            bfs(s,i);
        }
        printf("%d\n",dis);
    }
    return 0;
}

C++: #include <cstdio>
#include <iostream>
#include <queue>
#include <tuple>

#define MAX_W 1010
#define MAX_H 1010

using namespace std;

int w, h, n;
char sections[MAX_H][MAX_W];
bool visited[MAX_H][MAX_W];
int dx[] = {1, 0, -1, 0};
int dy[] = {0, -1, 0, 1};

tuple<int, int, int> bfs(queue<tuple<int, int, int> > &que, int hp) {
  if (que.empty()) return make_tuple(-1, -1, -1);
  int x, y, d;
  tie(x, y, d) = que.front(); que.pop();
  visited[y][x] = true;
  for (int i = 0; i < 4; ++i) {
    int nx = x + dx[i], ny = y + dy[i];
    if ((0 <= nx && nx < w && 0 <= ny && ny < h) &&
        (!visited[ny][nx] && sections[ny][nx] != 'X')) {
      if (sections[ny][nx] == ('0' + hp))
        return make_tuple(nx, ny, d + 1);
      else {
        visited[ny][nx] = true;
        que.push(make_tuple(nx, ny, d + 1));
      }
    }
  }
  return bfs(que, hp);
}

int main() {
  scanf("%d %d %d", &h, &w, &n);
  for (int i = 0; i < h; ++i) {
    scanf("%s", sections[i]);
  }

  int sx, sy;
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      if (sections[i][j] == 'S') {
        sx = j; sy = i;
      }
    }
  }

  int ans = 0;
  queue<tuple<int, int, int> > que;
  que.push(make_tuple(sx, sy, 0));
  for (int hp = 1; hp <= n; ++hp) {
    for (int i = 0; i < h; ++i) {
      for (int j = 0; j < w; ++j) {
        visited[i][j] = false;
      }
    }
    int x, y, d;
    tie(x, y, d) = bfs(que, hp);
    ans += d;
    que = queue<tuple<int, int, int> >();
    que.push(make_tuple(x, y, 0));
  }
  printf("%d\n", ans);
  
  return 0;
}