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<algorithm>
#include<map>
using namespace std;
#define MAX 1001

int h, w, n;
char city[MAX][MAX];
int step[10];
int direc1[4] = { -1,0,1,0 }, direc2[4] = { 0,1,0,-1 };

void dfs(char (&nowcity)[MAX][MAX], int nowstep, bool find, int nowi, int nowj, int nowpower, map<int, int> visited) {
	if (find) {
		if (step[nowpower-1] == -1) {
			step[nowpower-1] = nowstep;
		}
		else
		{
			step[nowpower-1] = min(step[nowpower-1], nowstep);
		}
		return;
	}
	if (step[nowpower] != -1) {
		if (nowstep >= step[nowpower]) {
			return;
		}
	}
	for (int i = 0; i < 4; i++) {
		if (nowi + direc1[i] >= 0 && nowi + direc1[i] < h&&nowj + direc2[i] >= 0 && nowj + direc2[i] < w) {

			if (nowcity[nowi + direc1[i]][nowj + direc2[i]] == '.') {
				if (!visited[(nowi + direc1[i]) * w + nowj + direc2[i]]) {
					visited[(nowi + direc1[i]) * w + nowj + direc2[i]]=1;
					dfs(nowcity, nowstep + 1, false, nowi + direc1[i], nowj + direc2[i], nowpower, visited);
				}	
			}
			else if (nowcity[nowi + direc1[i]][nowj + direc2[i]] >= '0'&&nowcity[nowi + direc1[i]][nowj + direc2[i]] <= '9')
			{
				int num = nowcity[nowi + direc1[i]][nowj + direc2[i]] - '0';
				if (nowpower == num) {					
					//nowcity[nowi + direc1[i]][nowj + direc2[i]] = '.';
					/*visited.clear();
					visited[(nowi + direc1[i]) * w + nowj + direc2[i]] =1;*/
					dfs(nowcity, nowstep + 1, true, nowi + direc1[i], nowj + direc2[i], nowpower,visited);
				}
				else {
					if (!visited[(nowi + direc1[i]) * w + nowj + direc2[i]]) {
						visited[(nowi + direc1[i]) * w + nowj + direc2[i]] =1;
						dfs(nowcity, nowstep + 1, false, nowi + direc1[i], nowj + direc2[i], nowpower,visited);
					}				
				}
			}
		}
	}
}



int main() {
	cin >> h >> w >> n;
	int nowi[10], nowj[10];
	
	for (int i = 0; i < h; i++)
	{
		for (int j = 0; j < w; j++)
		{
			cin >> city[i][j];
			if (city[i][j] == 'S') {
				nowi[0] = i;
				nowj[0] = j;
				city[i][j] = '.';
			}
			if (city[i][j] >= '0'&&city[i][j] <= '9') {
				nowi[city[i][j] - '0'] = i;
				nowj[city[i][j] - '0'] = j;
			}
		}
	}
	for (int i = 0; i < 10; i++) {
		step[i] = -1;
	}
	map<int, int>visited;
	for (int i = 0; i < n; i++) {
		visited.clear();
		visited[nowi[i] * w + nowj[i]] = 1;
		dfs(city, 0, false, nowi[i], nowj[i], i+1, visited);
	}
	int sum=0;
	for (int i = 0; i < n; i++) {
		sum += step[i];
	}
	cout << sum << endl;
	//system("pause");
	return 0;
}

C++: #include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
typedef pair<int,int> P;
int N,M,L,sx,sy,gx,gy,num;
const int INF = 100000000;
char maze[1100][1100];
int d[1100][1100];
int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};
P s[10];
void bfs()
{
	queue<P> que;
	for(int i=0;i<N;i++)
		for(int j=0;j<M;j++)
			d[i][j]=INF;
		que.push(P(sx,sy));
		d[sx][sy]=0;
	while(que.size())
	{
		P p=que.front() ;que.pop() ;
		if(p.first ==gx && p.second ==gy) break;
		for(int i=0;i<4;i++)
			{
				int nx=p.first +dx[i],ny=p.second +dy[i];
				if(nx>=0 && nx<N && ny>=0 && ny<M && maze[nx][ny]!='X' && d[nx][ny]==INF)
				{
					que.push(P(nx,ny));
					d[nx][ny]=d[p.first ][p.second ]+1; 
				}   
			}
	}
}
void solve()
{
	for(int i=0;i<L;i++)
	{
		sx=s[i].first ,sy=s[i].second;
		gx=s[i+1].first ,gy=s[i+1].second;
		bfs();
		num+=d[gx][gy];
	}
	printf("%d\n",num);
}
int main()
{
	while(~scanf("%d %d %d",&N,&M,&L))
	{
		num=0;
		for(int i=0;i<N;i++)
			for(int j=0;j<M;j++)
			{
				scanf("\n%c",&maze[i][j]);
				if(maze[i][j]=='S')
				s[0].first=i ,s[0].second=j ; 
				else if(maze[i][j]<='9' && maze[i][j] >='1')
				s[maze[i][j]-'0'].first =i,s[maze[i][j]-'0'].second =j;
			}
		solve();
	}
	return 0;
}

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

using namespace std;
const static int SIDE_LEN_MAX = 1000;
int field[ SIDE_LEN_MAX + 2 ][ SIDE_LEN_MAX + 2 ];
int visit_data[ SIDE_LEN_MAX + 2 ][ SIDE_LEN_MAX + 2 ]; // zero-initialized.
struct position {
  int r, c;
  int step_n;
};

bool enqueue( queue<position> &posq, int r, int c, int step_n, int level ) {
  position newpos;
  if( visit_data[ r ][ c ] != level && field[ r ][ c ] != 'X' ) {
    newpos.r = r;
    newpos.c = c;
    newpos.step_n = step_n;
    visit_data[ r ][ c ] = level;
    posq.push( newpos );
    return true;
  }
  return false;
}

int main() {
  int h, w, n;
  position pos;
  queue<position> posq;
  int level = 1;

  cin >> h >> w >> n;
  for( int c = 0; c <= SIDE_LEN_MAX + 1; c++ ) {
    field[ 0 ][ c ] = 'X';
    field[ h + 1 ][ c ] = 'X';
  }

  for( int r = 1; r <= h; r++ ) {
    string line;
    cin >> line;
    field[ r ][ 0 ] = 'X';
    for( int c = 1; c <= w; c++ ) {
      field[ r ][ c ] = line[ c - 1 ];
      if( field[ r ][ c ] == 'S' ) {
        enqueue( posq, r, c, 0, level );
      }
    }
    field[ r ][ w + 1 ] = 'X';
  }

  while( 1 ) {
    pos = posq.front();
    posq.pop();
    if(
        '1' <= field[ pos.r ][ pos.c ] &&
        field[ pos.r ][ pos.c ] <= '9' &&
        level == field[ pos.r ][ pos.c ] - '0'
    ) {
      while( posq.size() > 0 ){ posq.pop(); }
      posq.push( pos );
      if( ++level == n + 1 ) {
        cout << pos.step_n << endl;
        break;
      }
    }
    enqueue( posq, pos.r - 1, pos.c    , pos.step_n + 1, level );
    enqueue( posq, pos.r    , pos.c - 1, pos.step_n + 1, level );
    enqueue( posq, pos.r + 1, pos.c    , pos.step_n + 1, level );
    enqueue( posq, pos.r    , pos.c + 1, pos.step_n + 1, level );
  }
  

  return EXIT_SUCCESS;
}