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 <queue>
using namespace std;
#define MAXN 1001
char A[MAXN][MAXN];
int w,h,n;
int s[2];

void input()
{
    cin>>h>>w>>n;
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            cin>>A[i][j];
            if(A[i][j]=='S'){
                s[0]=i;
                s[1]=j;
            }
        }
    }
}

int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
using P = pair<pair<int,int>,int>;

int known[MAXN][MAXN];

int bfs(int& x, int& y, char k)
{
    queue<P>que;
    que.push(P(make_pair(x, y), 0));
    while(!que.empty()){
        P cur = que.front();
        // cout<<"*"<<cur.first.first<<" "<<cur.first.second<<endl;
        que.pop();
        if(A[cur.first.first][cur.first.second]==k){
            x = cur.first.first;
            y = cur.first.second;
            return cur.second;
        }
        for(int i=0;i<4;i++){
            int nx = cur.first.first+dx[i];
            int ny = cur.first.second+dy[i];
            if(0<=nx&&nx<h && 0<=ny&&ny<w && A[nx][ny]!='X' && !known[nx][ny]){
                que.push(P(make_pair(nx, ny), cur.second+1));
                known[nx][ny]=1;
            }
        }
    }
    return 0x3fffffff;
}

int main()
{
    input();
    int res = 0;
    int x, y;
    x = s[0];
    y = s[1];

    for(int i=1;i<=n;i++){
        memset(known, 0, sizeof(int)*MAXN*MAXN);
        int tmp = bfs(x, y, '0'+i);
        res += tmp;
    }
    cout<<res<<endl;
    return 0;
}

C++: #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>

using namespace std;

inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;}
template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();}
template<class T> inline T sqr(T x) {return x*x;}

typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef long long ll;

#define all(a)  (a).begin(),(a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define pb push_back
#define mp make_pair
#define each(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define exist(s,e) ((s).find(e)!=(s).end())
#define range(i,a,b) for(int i=(a);i<(b);++i)
#define rep(i,n)  range(i,0,n)
#define clr(a,b) memset((a), (b) ,sizeof(a))
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;

const double eps = 1e-10;
const double pi  = acos(-1.0);
const ll inf =1LL << 62;
const int  INF = 1 << 30;
struct node {
	int x;
	int y;
	int c;
};

bool dis[1010][1010];
int nx[10];
int ny[10];
string maze[1010];
int hmax=1;

int main(void){
	int H,W,n;
	cin >> H >> W >> n;
	rep(i,H) cin >> maze[i];
	node init;
	rep(i,H) rep(j,W){
		if(maze[i][j]=='S'){
			nx[0]=j;
			ny[0]=i;
		}else if(isdigit(maze[i][j])){
			nx[maze[i][j]-'0']=j;
			ny[maze[i][j]-'0']=i;
		}
	}
	int ans=0;
	rep(j,n){
		rep(k,H)rep(l,W) dis[k][l]=false;
		init.x=nx[j];
		init.y=ny[j];
		init.c=0;
		queue <node > q;
		q.push(init);
		int dx[4]={1,0,-1,0};
		int dy[4]={0,1,0,-1};
		while(!q.empty()){
			node cur;
			cur=q.front();q.pop();
			// テァツ渉セテ・ツ慊ィテ、ツスツ催ァツスツョテ」ツ?ョテ・ツ按、テ・ツョツ堙・ツ?ヲテァツ青?
			if(dis[cur.y][cur.x])
				continue;
			else
				dis[cur.y][cur.x]=true;
			if(hmax==(maze[cur.y][cur.x]-'0')){
				ans+=cur.c;
				hmax++;
				break;
			}
			//テ」ツ??ヲツャツ。テ」ツ?ョテァツ環カテヲツ?凝」ツ?クテ」ツ?ョテゥツ?キテァツァツサ
			rep(i,4){
				node next;
				next.x=cur.x+dx[i];
				next.y=cur.y+dy[i];
				next.c=cur.c+1;
				if(0<=next.x&&next.x<W&&0<=next.y&&next.y<H&&maze[next.y][next.x]!='X')
					q.push(next);
			}	
		}
	}
	cout << ans << endl;
	return 0;
}

C++: #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
#define MAXN 1005
using namespace std;

struct node {
	int i;
	int j;
	char val;
};

int H, W, N;//H(1 <= H <= 1000)、W(1 <= W <=1000)、N(1 <= N <= 9)
char m[MAXN][MAXN];
queue<node> q;

bool flag = 0;
int t1 = 0;
char flag_m[MAXN][MAXN];
void search(int i, int j, char val)
{
	if (flag_m[i][j]<val) {
		if (m[i][j] == 'X')
		{
			return;
		}
		if (m[i][j] == '.' || m[i][j] != val)
		{
			q.push({ i, j, val });
			//flag_m[i][j] = true;
			t1++;
		}
		if (m[i][j] == val)
		{
			if (val ==(char)('0' + N))
			{
				flag = 1;
			}
			else
			{
				q.push({ i, j, val + 1 });
				//flag_m[i][j] = true;
				m[i][j] = '.';
				t1++;
			}
		}
	}
	return;
}
int main()
{
	int si, sj;
	scanf("%d %d %d", &H, &W, &N);
	for (int i = 1; i <= H; i++)
	{
		getchar();
		for (int j = 1; j <= W; j++)
		{
			scanf("%c", &(m[i][j]));
			if (m[i][j] == 'S')
			{
				si = i;
				sj = j;
			}
		}
	}

	//

	q.push({ si, sj, '1' });
	memset(flag_m, '0', sizeof(flag_m));
	int t = 1;
	int time = 0;

	while (!q.empty() && (!flag))
	{
		time++;
		t1 = 0;
		while (t-- && (!flag))
		{
			node n1 = q.front(); q.pop();
			si = n1.i; sj = n1.j;
			flag_m[si][sj] = n1.val;
			if (si > 1)
			{
				search(si - 1, sj, n1.val);
			}
			if (si < H)
			{
				search(si + 1, sj, n1.val);
			}
			if (sj > 1)
			{
				search(si, sj - 1, n1.val);
			}
			if (sj < W)
			{
				search(si, sj + 1, n1.val);
			}

		}
		t = t1;
	}
	printf("%d\n", time);
	return 0;
}

C++: #include <cstdio>
#include <iostream>
using namespace std;
int ans = 0;
int gh=0, gw=0;
const int max = INT_MAX / 2;
char c[1000][1000];
int d[1000][1000];
int mh[4] = { 1,0,-1,0 };
int mw[4] = { 0,1,0,-1 };
char hijou[9] = { '1','2','3','4','5','6','7','8','9' };
int  judge(int h, int w,int g) {
	if (c[h][w] ==hijou[g])
	{ 	gh = h;
	gw = w; 
	return d[h][w];
	}
	for (int i = 0; i < 4; i++) {
		int nh = h + mh[i];
		int nw = w + mh[i];
		if (nh >= 0 && nh < 1000 && nw>=0 && nh < 1000 && d[nh][nw] == max&&c[nh][nw] != 'X') {
			d[nh][nw] = d[h][w] + 1;
			judge(nh, nw,g);
		}
	}
}
int main() {
	int h, w, n,sh,sw;
	for (int i = 0; i < 1000;i++){
		for (int j = 0; j < 1000; j++)
		{
			c[i][j] = 'X'; 
		}
	}
	cin >> h >> w >> n;
	for (int i = 0; i < h; i++) {
		for (int j = 0; j < w;j++){
			cin >> c[i][j];
			if (c[i][j] == 'S') { sh = i; sw = j; }
		}
	}cout << sh << sw;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < 1000; j++) {
			for (int k = 0; k < 1000; k++)
				d[j][k] = max;
		}
	
		d[sh][sw] = 0;
		ans+=judge(sh, sw, i);
		sh = gh; sw = gw;
}
	cout << ans << endl;
	
}