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<algorithm>
#include<iostream>
#include<string.h>
#include<queue>

using namespace std;

typedef pair<int,int> P;
#define INF 1000000

int dx[4]={1,0,0,-1}, dy[4]={0,1,-1,0};
int d[1010][1010];
char r[1010][1010];
char point[10]={'S','1','2','3','4','5','6','7','8','9'};
int H,W,N;
int res=0;

int bfs(int ah,int aw,int bh,int bw){
  queue<P> que;
  for(int i=0;i<H;i++)
    for(int j=0;j<W;j++)
      d[i][j]=INF;

  d[ah][aw]=0;
  que.push(P(ah,aw));

  while(que.size()){
    P p= que.front();
    que.pop();
    if(p.first==bh && p.second==bw) break;

    for(int i=0;i<4;i++){
      int nh=p.first+dx[i], nw=p.second+dy[i];

      if(0<=nh && nh<H && 0<=nw && nw<W && r[nh][nw]!='X' && d[nh][nw]==INF){
        que.push(P(nh,nw));
        d[nh][nw]=d[p.first][p.second]+1;
      }
    }
  }
  return d[bh][bw];
}

void solve(){
  queue<P> kyu;
  for(int k=0;k<=N;k++){
    for(int i=0;i<H;i++){
      for(int j=0;j<W;j++){
        if(r[i][j]==point[k])
          kyu.push(P(i,j));
      }
    }
  }

  for(int i=0;i<N;i++){
    P p1=kyu.front();
    kyu.pop();
    P p2=kyu.front();
    res+=bfs(p1.first,p1.second,p2.first,p2.second);
  }

  printf("%d\n",res);

}


int main(){
  scanf("%d%d%d",&H,&W,&N);

  for(int i=0;i<H;i++)
    scanf("%s",&r[i]);

  solve();

  return 0;
}

C++: #include<bits/stdc++.h>
using namespace std;
queue <pair<int ,int> > po;
int memo[1005][1005],ans,h,w,n, miti[1005][1005];
char c;
bool flag=false;


int main(){

    cin >> h >> w >> n;
    fill(miti[0],miti[1004],100);

    for(int i=1;i<=h;i++){
        for(int j=1;j<=w;j++){
            cin >> c;
            if(c=='S'){
                po.push(make_pair(j,i));
                miti[j][i]=0;
            }else if(c=='X')miti[j][i]=100;
            else if(c=='.')miti[j][i]=0;
            else miti[j][i]=(c-'0')+10;
        }
    }

    for(int hp=1;hp<=n;hp++){
            flag=false;
           // printf("hp=%d\n",hp);

        while(!po.empty()){
        int px,py;
        px=po.front().first;
        py=po.front().second;
        po.pop();
        // printf("%d %d\n",px,py);

    int xx[4]={0,1,0,-1};
    int yy[4]={1,0,-1,0};

    if(px<1||py<1||px>w||py>h);
    else{
    for(int i=0;i<4;i++){
            if(miti[px+xx[i]][py+yy[i]]==hp+10){

                ans+=memo[px][py]+1;
               // printf("memo=%d\n",memo[px][py]);
               //   printf("%d=(%d %d)\nans=%d\n\n",hp,px+xx[i],py+yy[i],ans);
                flag=true;
                while(!po.empty())po.pop();
                po.push(make_pair(px+xx[i],py+yy[i]));
                fill(memo[0],memo[1004],0);
                break;
        }else if((miti[px+xx[i]][py+yy[i]]<hp||miti[px+xx[i]][py+yy[i]]>10)&&miti[px+xx[i]][py+yy[i]]!=100){
            po.push(make_pair(px+xx[i],py+yy[i]));
            memo[px+xx[i]][py+yy[i]]=memo[px][py]+1;
            if(miti[px+xx[i]][py+yy[i]]>10);
            else miti[px+xx[i]][py+yy[i]]=hp;
                }
            }
            if(flag==true)break;
    }
        }
    }


    cout << ans << endl;


return 0;
}

C++: #include<iostream>
#include<queue>
#include<algorithm>
#include<utility>
#include<cstring>
using namespace std;
typedef struct pos{
	int x,y,d;
}pos;
queue<pos> q1;
int a[1005][1005];
bool b[1005][1005];
int main(){
	int i,j,k;
	int h,w,n;
	int x,y;
	char ca;
	pos po;
	cin>>h>>w>>n;
	cin.tie(0);
	ios::sync_with_stdio(false);
	for(i=0;i<h;i++){
		for(j=0;j<w;j++){
			cin>>ca;
			if(ca=='.'){
				a[i][j]=0;
			}else if(ca=='S'){
				po.x=i; po.y=j; po.d=0;
				q1.push(po);
			}else if(ca=='X'){
				a[i][j]=-1;
			}else{
				k=1;
				for(char cs='1';cs<='9';cs++,k++){
					if(cs==ca){
						a[i][j]=k;
						break;
					}
				}
			}
		}
	}
	
	for(i=1;i<=n;i++){
		memset(b,false,sizeof(b));
		while(!q1.empty()){
			po=q1.front();
			q1.pop();
			x=po.x; y=po.y;
			if(x<0 || x>=h || y<0 || y>=w)continue;
			if(b[x][y] || a[x][y]==-1)continue;
			if(a[x][y]==i){
				break;
			}
			b[x][y]=true;
			po.d++;
			for(j=-1;j<=1;j++){
				for(k=-1;k<=1;k++){
					if((j+k)%2==0)continue;
					po.x=x+j; po.y=y+k;
					q1.push(po);
				}
			}
		}
		while(!q1.empty()){
			q1.pop();
		}
		q1.push(po);
	}
	cout<<po.d;
	return 0;
}

C++: #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <stack>
#include <array>
#include <deque>
#include <algorithm>
#include <utility>
#include <cstdint>
#include <functional>
#include <iomanip>
#include <numeric>
#include <assert.h>
#include <bitset>

#define MOD 1000000007
#define INF 11234567890
#define in std::cin
#define out std::cout
#define rep(i,N) for(LL i=0;i<N;++i)
typedef long long int LL;
typedef std::pair<LL, LL> P;
struct edge { LL to, cost; };

LL H, W, N;
std::string field[1123];
LL Sx, Sy, xy[11];
LL ans;

LL d[1123456];
std::vector<edge>G[1123456];
void dijkstra(LL s)
{
	std::priority_queue<P, std::vector<P>, std::greater<P>>que;
	std::fill(d, d + H * W + 1, INF);
	d[s] = 0;
	que.push(P(0, s));
	while (!que.empty())
	{
		P p = que.top(); que.pop();
		LL v = p.second;
		if (d[v] < p.first) { continue; }
		rep(i, G[v].size())
		{
			edge e = G[v][i];
			if (d[e.to] > d[v] + e.cost)
			{
				d[e.to] = d[v] + e.cost;
				que.push(P(d[e.to], e.to));
			}
		}
	}
}

int main()
{
	try {
		in >> H >> W >> N;
		rep(i, H) { in >> field[i]; }

		rep(h, H)
		{
			rep(w, W)
			{
				if (field[h][w] == 'X') { continue; }
				else if (field[h][w] == 'S') { Sx = h; Sy = w; }
				else if (field[h][w] != '.') { xy[field[h][w] - '0'] = h*W + w; }
				if (h < H - 1)
				{
					if (field[h + 1][w] != 'X')
					{
						G[h*W + w].push_back({ (h + 1)*W + w,1 });
						G[(h + 1)*W + w].push_back({ h*W + w,1 });
					}
				}
				if (w < W - 1)
				{
					if (field[h][w + 1] != 'X')
					{
						G[h*W + w].push_back({ h*W + (w + 1),1 });
						G[h*W + (w + 1)].push_back({ h*W + w,1 });
					}
				}
			}
		}
		dijkstra(Sx*W + Sy);
		rep(i, N)
		{
			ans += d[xy[i + 1]];
			dijkstra(xy[i + 1]);
		}

		out << ans << std::endl;
		return 0;
	}
	catch (std::bad_alloc) { return 0; }
	catch (...) { return 0; }
}