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<functional>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
char a[1000][1001],a2[1000][1001];
int main(void)
{
	int h,w,n,i,j,k,cnt,sum,sx,sy,x2,y2,x,y,nnn;
	int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};
	scanf("%d %d %d",&h,&w,&n);
	for(i=0;i<h;i++)	scanf("%s",a[i]);
	sum=0;
	for(i=0;i<h;i++)	{
		for(j=0;j<w;j++)	{
			if(a[i][j]=='S')	{
				sx=j;	sy=i;
			}
		}
	}
	for(i=1;i<=n;i++)	{
		queue<int> xx,yy,nn;
		for(j=0;j<h;j++)	strcpy(a2[j],a[j]);
		xx.push(sx);	yy.push(sy);	nn.push(0);
		while(!xx.empty() )	{
//			printf("size=%d\n",xx.size());
			x=xx.front();	y=yy.front();	nnn=nn.front();
			xx.pop();	yy.pop();	nn.pop();
			if(a2[y][x]-'0'==i)	{
				sum+=nnn;
				sx=x;	sy=y;
				break;
			}
			else {
				if(a2[y][x]!='X')	{
					a2[y][x]='X';
					for(k=0;k<4;k++)	{
						x2=x+dx[k];	y2=y+dy[k];
						if(x2>=0 && x2<w && y2>=0 && y2<h && a2[y2][x2]!='X')	{
							xx.push(x2);	yy.push(y2);	nn.push(nnn+1);
						}
					}
				}
			}
		}
//		while(xx.size()!=0)	{
//			xx.pop();	yy.pop();	nn.pop();
//		}
	}
	printf("%d\n",sum);
	return 0;
}

C++: #include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <functional>
#include <array>
#include <stack>
#include <queue>
#include <chrono>
#include <numeric>

#pragma warning(disable:4996)
#define REP(i,n) for(int i = 0 ; i < n ; ++i)
typedef long long Int;

using namespace std;

struct point{
	Int j, i,step;
	point(Int i_, Int j_,Int s) :i(i_), j(j_),step(s){}
};

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

queue<point> que;
char tile[1000][1000];
int H, W;
bool ed[1000][1000];

point solve(char target)
{
	while (!que.empty()){
		point now(que.front());
		//ed[now.i][now.j] = true;
		que.pop();
		REP(i, 4){
			int x = now.j + dx[i];
			int y = now.i + dy[i];

			if (x < 0 || y < 0 || x > W || y > H || ed[y][x])
				continue;

			if (tile[y][x] == target){
				return point(y, x,now.step+1);
			}

			if (tile[y][x] != 'X'){
				que.push(point(y, x, now.step + 1));
				ed[y][x] = true;
			}
		}
	}
}

int main()
{
	cin.tie(0); ios::sync_with_stdio(false);
	//fstream fs("input.txt");
	////////////ここから開始///////////
	int n(0);
	cin >> H >> W >> n;

	REP(i, 1000)REP(j, 1000)tile[i][j] = 'X';

	REP(i, H)REP(j, W)cin >> tile[i][j];

	REP(i, H)REP(j, W){ if (tile[i][j] == 'S')que.emplace(i, j, 0); }
	Int ans(0);
	for(int i = 0 ; i < n ; ++i){
		REP(i_1, H+1)REP(j_1, W+1){ ed[i_1][j_1] = false; }
		point t = solve('1' + i);
		que = {};
		que.emplace(t);
		ans = t.step;
	}
	
	cout << ans << endl;

	return 0;
}

C++: #include <cstdio>
#include <map>
#include <queue>
#include <string>

using namespace std;

const int INF = -1;
const int MAX_H = 1000;
const int MAX_W = 1000;
const int MAX_N = 9;

int H, W, N;
char field[MAX_H][MAX_W];
int d[MAX_H][MAX_W];
int sx, sy, gx, gy;
int power = 1;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};

typedef pair<int, int> P;

void reset_d() {
  for (int i = 0; i < H; i++)
    for(int j = 0; j < W; j++) d[i][j] = INF;
}

int bfs(int c) {
  queue<P> que;
  reset_d();
  d[sx][sy] = c;
  que.push(P(sx, sy));
  while(que.size()) {
    P p = que.front(); que.pop();
    for (int i = 0; i < 4; i++) {
      int nx = p.first + dx[i], ny = p.second + dy[i];
      if ( 0 <= nx && nx <= H && 0 <= ny && ny <= W && field[nx][ny] != 'X' && d[nx][ny] == INF) {
        d[nx][ny] = d[p.first][p.second] + 1;
        que.push(P(nx, ny));
        if (field[nx][ny] - '0' == power) {
          sx = nx;
          sy = ny;
          power++;
          return d[nx][ny];
        }
      }
    }
  }
  return INF;
}

void solve() {
  int c = 0;
  for (int i = 0; i < N; i++) {
    c = bfs(c);
  }
  printf("%d\n", c);
}


int main() {
  scanf("%d %d %d", &H, &W, &N);
  for (int i = 0; i < H; i++) {
    scanf("%s", field[i]);
  }
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      if (field[i][j] == 'S') {
        sx = i;
        sy = j;
      }
      if (field[i][j] == 'G') {
        gx = i;
        gy = j;
      }
    }
  }
  solve();
  return 0;
}

C++: #include <iostream>
#include <cstdio>
//#include <cmath>
#include <vector>
#include <cstring>
#include <string>
#include <algorithm>
#include <string>
#include <set>
#include <functional>
#include <numeric>
#include <sstream>
#include <stack>
#include <map>
#include <queue>

#define CL(arr, val)    memset(arr, val, sizeof(arr))

#define ll long long
#define inf 0x7f7f7f7f
#define lc l,m,rt<<1
#define rc m + 1,r,rt<<1|1
#define pi acos(-1.0)

#define L(x)    (x) << 1
#define R(x)    (x) << 1 | 1
#define MID(l, r)   (l + r) >> 1
#define Min(x, y)   (x) < (y) ? (x) : (y)
#define Max(x, y)   (x) < (y) ? (y) : (x)
#define E(x)        (1 << (x))
#define iabs(x)     (x) < 0 ? -(x) : (x)
#define OUT(x)  printf("%I64d\n", x)
#define lowbit(x)   (x)&(-x)
#define Read()  freopen("a.txt", "r", stdin)
#define Write() freopen("dout.txt", "w", stdout);
#define maxn 1000000000
#define N 1010
using namespace std;

int h,w,x;
int dir[4][2]={-1,0,0,1,0,-1,1,0};
typedef pair<int,int> P;
P p;
char maze[N][N];
int d[N][N];

int bfs(char c)
{
    queue<P>que;
    for(int i=0;i<h;i++)
        for(int j=0;j<w;j++) d[i][j]=maxn;
    que.push(p);
    d[p.first][p.second]=0;
    P p1,p2;
    while(que.size())
    {
        p1=que.front(); que.pop();
        if(maze[p1.first][p1.second]==c)
        {
            p=p1; break;
        }
        for(int i=0;i<4;i++)
        {
            p2.first=p1.first+dir[i][0];
            p2.second=p1.second+dir[i][1];
            if(p2.first>=0&&p2.first<h&&p2.second>=0&&p2.second<w&&maze[p2.first][p2.second]!='X'&&d[p2.first][p2.second]==maxn)
            {
                que.push(p2);
                d[p2.first][p2.second]=d[p1.first][p1.second]+1;
            }
        }
    }
    return d[p.first][p.second];
}

int main()
{
    //freopen("a.txt","r",stdin);
    while(~scanf("%d%d%d",&h,&w,&x))
    {
        getchar();
        int sum=0;
        for(int i=0;i<h;i++)
        {
            scanf("%s",maze[i]);
            //printf("%s\n",maze[i]);
            for(int j=0;j<w;j++)
            {
                if(maze[i][j]=='S')
                {
                    p.first=i;
                    p.second=j;
                }
            }
        }
        //printf("%d %d\n",p1.first,p1.second);
        for(int i=1;i<=x;i++)
        {
            sum+=bfs('0'+i);
        }
        printf("%d\n",sum);
    }
   return 0;
}