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

struct mouse{
	int y, x, dis;
};

char stage[1000][1000];
int ng[1000][1000] = {};
int main(){
	int h, w, n;
	mouse s;
	s.dis = 0;
	cin >> h >> w >> n;
	for (int i = 0; i < h; i++){
		cin >> stage[i];
		for (int j = 0; j < w; j++){
			if (stage[i][j] == 'S'){
				s.y = i;
				s.x = j;
			}
			else if (stage[i][j] != 'X' && stage[i][j] != '.'){
				stage[i][j] -= '0';
			}
		}
	}

	int ny, nx;
	int situ_y[4] = { -1, 0, 1, 0 }, situ_x[4] = { 0, 1, 0, -1 };
	for (int target = 1; target <= n; target++){
		queue<mouse> mickey;
		mouse m_c;
		mickey.push(s);
		while (1){
			m_c = mickey.front();
			if (stage[m_c.y][m_c.x] == target){
				s.y = m_c.y;
				s.x = m_c.x;
				s.dis = m_c.dis;
				break;
			}
			if ((m_c.dis != 0 && ng[m_c.y][m_c.x] == m_c.dis)
				|| stage[m_c.y][m_c.x] == 'X'){
				mickey.pop();
				continue;
			}
			ng[m_c.y][m_c.x] = m_c.dis;
			for (int i = 0; i < 4; i++){
				m_c = mickey.front();
				ny = m_c.y + situ_y[i];
				nx = m_c.x + situ_x[i];
				if (ny < 0 || h <= ny || nx < 0 || w <= nx) continue;
				m_c.y = ny;
				m_c.x = nx;
				m_c.dis++;
				mickey.push(m_c);
			}
			mickey.pop();
		}
	}
	printf("%d\n", s.dis);
	return 0;
}

C++: #include <algorithm>
#include <cmath>
#include <climits>
#include <cstring>
#include <deque>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map> //pair is also included in this library
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <vector>

#define REP(i, s, n) for(int i = (int)(s); i < (int)(n); i++)
#define fst first
#define snd second
#define MP make_pair //incase c++11 or later is not available

using namespace std;

typedef long long int ll;
typedef vector<int> VI;
typedef vector<ll> VL;
typedef pair<int, int> PII;
typedef pair<ll, ll> PLL;

//prefer define statement
//for reason that const int ver. of INF will raise a silly warning (unused variable)
#define INF (INT_MAX/3)
#define LIM_INF (INT_MAX)
//const int INF = INT_MAX/3;

/*------------------------------------------------------------------------------*/

int cost[1100][1100];

int main(){
  int H, W, N;
  cin >> H >> W >> N;
  vector<string> s;

  s.push_back(string(W+2, 'X'));
  REP(i, 0, H){
    string tmp;
    cin >> tmp;
    s.push_back('X' + tmp + 'X');
  }
  s.push_back(string(W+2, 'X'));

  vector<PII> v(N+1);
  REP(i, 0, H+2){
    REP(j, 0, W+2){
      char c = s[i][j];
      if(c >= '1' && c <= '9'){
        v[c-'0'] = {i, j};
      } else if(c == 'S'){
        v[0] = {i, j};
      }
    }
    //cout << s[i] << endl;
  }

  int dest = 0, res = 0;
  REP(i, 0, N){
    queue<PII> q;
    q.push(v[dest]);
    memset(cost, -1, sizeof(cost));
    cost[v[dest].fst][v[dest].snd] = 0;
    while(!q.empty()){
      PII a = q.front(); q.pop();
      const int dx[4] = {-1, 0, 1, 0};
      const int dy[4] = {0, -1, 0, 1};
      if(s[a.fst][a.snd] == i + '1'){
        res += cost[a.fst][a.snd];
        dest++;
        break;
      }
      REP(i, 0, 4){
        int ny = a.fst + dy[i];
        int nx = a.snd + dx[i];
        if(s[ny][nx] != 'X' && !(cost[ny][nx] + 1)){//cost[ny][nx] + 1 == 0 if not searched
          cost[ny][nx] = cost[a.fst][a.snd] + 1;
          q.push({ny, nx});
        }
      }
    }
  }
  cout << res << endl;

  return 0;
}

C++: #include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#define INF 10000000
using namespace std;
struct data{
    int x,y;
};
int H,W,N;
int ans[1001][1001];
char field[1001][1001];
long long int cou;
int dx[]={0,1,0,-1},dy[]={1,0,-1,0};
int main(){
    data s;
    cin>>H>>W>>N;
    for(int i=0;i<H;i++){
        for(int j=0;j<W;j++){
            cin>>field[i][j];
            if(field[i][j]=='S'){
                s.x=i,s.y=j;
            }
        }

    }
    for(int l=1;l<=N;l++){
        data g;
        g.x=1,g.y=1;
        for(int i=0;i<H;i++){
            for(int j=0;j<W;j++){
                ans[i][j]=INF;
                if(field[i][j]==l+'0'){
                    g.x=i,g.y=j;
                    //cout<<l+'0'<<endl;
                }
            }
        }
        ans[s.x][s.y]=0;
        queue <data> q;
        q.push(s);
        while(!q.empty()){
            data now;
            now=q.front();
            q.pop();
            if(now.x==g.x&&now.y==g.y)break;
            int nex,ney;
            for(int i=0;i<4;i++){
                nex=now.x+dx[i];
                ney=now.y+dy[i];
                if(nex>=0&&nex<H&&ney>=0&&ney<W&&ans[nex][ney]==INF&&field[nex][ney]!='X'){
                    data nowne;
                    nowne.x=nex,nowne.y=ney;
                    q.push(nowne);
                    ans[nex][ney]=ans[now.x][now.y]+1;
                }
            }
        }
        cou+=ans[g.x][g.y];
        s=g;
    }
    cout<<cou<<endl;
return 0;
}

C++: #include <bits/stdc++.h>
using namespace std;
 
int h, w, n;
char m[1010][1010];
int d[1010][1010];
int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};
 
void init()
{
  for (int i = 0; i < h; i++){
    for (int j = 0; j < w; j++){
      d[i][j] = 1e9 + 9;
    }
  }
}
 
int main()
{
  int sx, sy;
 
  cin >> h >> w >> n;
  for (int i = 0; i < h; i++){
    for (int j = 0; j < w; j++){
      cin >> m[i][j];
      if (m[i][j] == 'S') sx = j, sy = i;
    }
  }
 
  int ans = 0;
  for (int i = 1; i <= n; i++){
    queue<pair<int, int> > q;
    q.push(make_pair(sy, sx));
 
    init();
    d[sy][sx] = 0;
    while (!q.empty()){
      pair<int, int> nv = q.front();
      q.pop();
 
      if (m[nv.first][nv.second] == '0' + i){
        sy = nv.first;
        sx = nv.second;
        ans += d[sy][sx];
        while (!q.empty()) q.pop();
        break;
      }
 
      for (int j = 0; j < 4; j++){
        int ny = nv.first + dy[j];
        int nx = nv.second + dx[j];
        if (ny < 0 || h <= ny || nx < 0 || w <= nx) continue;
        if (d[ny][nx] != 1e9 + 9) continue;
        if (m[ny][nx] == 'X') continue;
        d[ny][nx] = d[nv.first][nv.second] + 1;
        q.push(make_pair(ny, nx));
      }
    }
  }
 
  cout << ans << endl;
}