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 <vector>
#include <map>
#include <queue>
using namespace std;

class DAT{
public:
  int x;
  int y;
  int total;
  bool operator<(const DAT &A)const{
    return A.total < total;
  }
};

int main(void){
  int h,w,n;
  cin>>h>>w>>n;
  vector<string> field(h);
  map<int,pair<int,int> > ps;
  for(int i=0;i<h;++i){
    int j;
    cin>>field[i];
    if((j = field[i].find('S')) != string::npos)
      ps[0] = make_pair(j,i);
    for(char c='1';c<='9';++c)
      if((j = field[i].find(c)) != string::npos)
        ps[c-'0'] = make_pair(j,i);
  }
  int ans=0;
  for(int i=0;i<n;++i){
    int sx = ps[i].first, sy = ps[i].second;
    vector<vector<int> > dist(h);
    for(int j=0;j<h;++j){
    	dist[j]=vector<int>(w);
    	for(int k=0;k<w;++k){
    		dist[j][k]=h*w;
    	}
    }
    priority_queue<DAT> Q;
    DAT start;
    start.x = sx; start.y = sy; start.total = 0;
    Q.push(start);
    int sum = 0;
    while(!Q.empty()){
      DAT dat = Q.top();Q.pop();
      if(dist[dat.y][dat.x] < dat.total) continue;
      if(dat.x == ps[i+1].first && dat.y == ps[i+1].second){sum=dat.total;break;}
      if(field[dat.y][dat.x] == '.' || field[dat.y][dat.x] == 'S' || ('1'<=field[dat.y][dat.x] && field[dat.y][dat.x] <= '9')){
        dist[dat.y][dat.x] = dat.total;
        if(dat.x>0){
          DAT nxt;
          nxt.x=dat.x-1;nxt.y=dat.y;nxt.total=dat.total+1;
          Q.push(nxt);
        }
        if(dat.y>0){
          DAT nxt;
          nxt.x=dat.x;nxt.y=dat.y-1;nxt.total=dat.total+1;
          Q.push(nxt);
        }
        if(dat.x<w-1){
          DAT nxt;
          nxt.x=dat.x+1;nxt.y=dat.y;nxt.total=dat.total+1;
          Q.push(nxt);
        }
        if(dat.y<h-1){
          DAT nxt;
          nxt.x=dat.x;nxt.y=dat.y+1;nxt.total=dat.total+1;
          Q.push(nxt);
        }
      }
    }
    ans+=sum;
  }
  cout<<ans<<endl;
  return 0;
}

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

typedef struct status
{
	int x;
	int y;
	int hp;
	int time;
	int ate;
}status;

std::queue<status> que;

char field[1000][1000];
bool visited[1000][1000];

int bfs(int xs,int ys,int h,int w,int n);

int main()
{
	char buf[1024];
	int h,w,n,xs,ys;

	std::cin>>h>>w>>n;
	std::cin.getline(buf,1024);
	for(int i=0;i<h;i++)
	{
		std::cin.getline(buf,w+2);
		for(int j=0;j<w;j++)
		{
			field[i][j]=buf[j];
			if(field[i][j]=='S')
			{
				xs=j;
				ys=i;
			}
		}
	}
	std::cout<<bfs(xs,ys,h,w,n)<<std::endl;
	
	return 0;
}

int bfs(int xs,int ys,int h,int w,int n)
{
	status survey,next;
	int cost,t;
	memset(visited,0,sizeof(visited));
	survey.x=xs;
	survey.y=ys;
	survey.hp=1;
	survey.ate=0;
	survey.time=0;
	t=0;
	que.push(survey);
	while(!que.empty())
	{
		survey=que.front();
		que.pop();
		next=survey;
		
		if(field[survey.y][survey.x]!='.'&&field[survey.y][survey.x]!='S')
		{
			cost=field[survey.y][survey.x]-'0';
			if(survey.hp==cost)
			{
				next.ate++;
				next.hp++;
				while(!que.empty()){que.pop();}
				memset(visited,0,sizeof(visited));
				visited[next.y][next.x]=true;
				if(next.ate==n)break;
			}
		}
		next.time++;

		if(survey.x>0&&field[next.y][next.x-1]!='X')
		{
			if(!visited[next.y][next.x-1])
			{
				next.x--;
				que.push(next);
				visited[next.y][next.x]=true;
				next.x++;
			}
		}
		if(survey.x<w-1&&field[next.y][next.x+1]!='X')
		{
			if(!visited[next.y][next.x+1])
			{
				next.x++;
				que.push(next);
				visited[next.y][next.x]=true;
				next.x--;
			}
		}
		if(survey.y>0&&field[next.y-1][next.x]!='X')
		{
			if(!visited[next.y-1][next.x])
			{
				next.y--;
				que.push(next);
				visited[next.y][next.x]=true;
				next.y++;
			}
		}
		if(survey.y<h-1&&field[next.y+1][next.x]!='X')
		{
			if(!visited[next.y+1][next.x])
			{
				next.y++;
				que.push(next);
				visited[next.y][next.x]=true;
				next.y--;
			}
		}
	}
	return survey.time;
}

C++: //#define LOCAL

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>

#define SIZE 1010

using namespace std;

char map[SIZE][SIZE];
int dir[][2] = {0, 1, 0, -1, 1, 0, -1, 0};

int bfs(int &x, int &y, int h, int w, int target){
	int step[SIZE][SIZE];
	for(int i = 0; i < h; i++)
		fill(step[i], step[i] + w, -1);
	step[x][y] = 0;

	queue<pair<int, int> > q;
	q.push(make_pair(x, y));

	while(!q.empty()){
		pair<int, int> temp = q.front();
		q.pop();

		if(map[temp.first][temp.second] == target + '0'){
			x = temp.first;
			y = temp.second;
			return step[x][y];
		}

		for(int i = 0; i < 4; i++){
			int newx = temp.first + dir[i][0];
			int newy = temp.second + dir[i][1];

			if(0 <= newx && newx < h && 0 <= newy && newy < w
				&& step[newx][newy] == -1 
				&& map[newx][newy] != 'X'){
				q.push(make_pair(newx, newy));
				step[newx][newy] = step[temp.first][temp.second] + 1;
			}
		}
	}
}

int main(void){
#ifdef LOCAL
	freopen("data.in", "r", stdin);
#endif
	int n, w, h;
	int x, y;

	scanf("%d%d%d", &h, &w, &n);
	getchar();
	for(int i = 0; i < h; i++){
		for(int j = 0; j < w; j++){
			scanf("%c", &map[i][j]);

			if(map[i][j] == 'S'){
				x = i;
				y = j;
			}
		}
		getchar();
	}

	int result = 0;
	for(int i = 1; i <= n; i++)
		result += bfs(x, y, h, w, i);

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

	return 0;
}