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 <cstring>
#include <queue>
using namespace std;
class Node{
public:
    int x,y,cost;
    Node(int x,int y,int cost):x(x),y(y),cost(cost){}
    Node(){}
};
char map[1010][1010];
bool flag[1010][1010];
int h,w,n;
int bfs(char s,char e);
int main()
{
    cin>>h>>w>>n;
    for(int j=0;j<h;++j){
        for(int i=0;i<w;++i){
            cin>>map[i][j];
        }
    }
    int ans=0;
    char f=n+'0';
    ans+=bfs('S','1');
    for(char S='1';S<f;++S){
        ans+=bfs(S,S+1);
    }
    cout<<ans<<endl;
    return 0;
}
int bfs(char s,char e)
{
    int dx[4]={0,0,1,-1},dy[4]={-1,1,0,0};
    memset(flag, 0, sizeof(flag));
    queue<Node> q;
    for(int j=0;j<h;++j){
        for(int i=0;i<w;++i){
            if(map[i][j]==s){
                q.push(Node(i,j,0));
            }
        }
    }
    while(!q.empty())
    {
        Node t=q.front();q.pop();
        if(map[t.x][t.y]==e)return t.cost;
        if(flag[t.x][t.y])continue;
        for(int i=0;i<4;++i){
            Node next=t;
            next.cost++;
            next.x+=dx[i];next.y+=dy[i];
            if(next.x>=0&&next.y>=0&&next.x<w&&next.y<h&&map[next.x][next.y]!='X')q.push(next);
        }
        flag[t.x][t.y]=true;
    }
}

C++: #include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#include<stack>
#include<queue>
#include<cctype>
#define INF 100000000
using namespace std;

struct  coor
{
	int x, y;
};

char map[1002][1002];
int time[1002][1002];
int vis[1002][1002];
int dx[4] = { 0,1,0,-1 };
int dy[4] = { 1,0,-1,0 };
int h, w, n;
coor s;
coor fac[9];
int phy;
int ans;


int bfs(coor fa)
{
	coor next;
	coor now;
	queue<coor>q;
	q.push(s);
	vis[s.x][s.y] = 1;
	while (!q.empty())
	{
		now = q.front();
		q.pop();
		if (now.x == fa.x&&now.y == fa.y)
		{
			break;
		}
		vis[now.x][now.y] = 1;
		for (int i = 0;i < 4;i++)
		{
			next.x = now.x + dx[i];
			next.y = now.y + dy[i];
			if (map[next.x][next.y] != 'X'&&next.x >= 0&& next.x < h &&next.y >= 0 && next.y < w&&!vis[next.x][next.y])
			{
				time[next.x][next.y] = time[now.x][now.y] + 1;
				q.push(next);
			}
		}
	}
	return time[fa.x][fa.y];
}

void timeinit(coor st)
{
	for (int i = 0;i < h;i++)
	{
		for (int j = 0;j < w;j++)
		{
			if (map[i][j] != 'X')
				time[i][j] = INF;
		}
	}
	time[st.x][st.y] = 0;

}
int main()
{
	while (~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]);
				time[i][j] = INF;
				if (map[i][j] == 'S') { map[i][j] = '.';s.x = i;s.y = j; }
				if (isdigit(map[i][j]))
				{
					fac[map[i][j] - '0'].x = i;
					fac[map[i][j] - '0'].y = j;
				}
			}
			getchar();
		}

		phy = 1;
		time[s.x][s.y] = 0;
		ans = 0;
		for (int i = 1;i <= n;i++)
		{
			memset(vis, 0, sizeof(vis));
			ans += bfs(fac[i]);
			s.x = fac[i].x;
			s.y = fac[i].y;
			timeinit(s);
		}
		printf("%d\n", ans);
	}
	return 0;
}

C++: #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <cstring>
#include <sstream>
#include <cassert>
using namespace std;
static const double EPS = 1e-10;
typedef long long ll;
typedef pair<int,int> PI;
#define rep(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
int dx[]={0,1,0,-1},dy[]={1,0,-1,0};
 
typedef struct{
  short x,y;
  int cost;
  short ch;
}mouse;
mouse Q[100000];
int s,num;
 
mouse t;
short cx,cy,nx,ny,ch,nch,h,w,n;
int cost;
 
main(){
  scanf("%d%d%d ",&h,&w,&n);
  short maxch[h][w];
  char ku[h][w];
  
  rep(i,h)fread(ku[i],1,w+1,stdin);
 
 
  rep(i,h)rep(j,w){
    if(ku[i][j]=='S')cx=i,cy=j;
    maxch[i][j]=-1;
  }
 
 
  Q[s+num++]=(mouse){cx,cy,0,0};
  maxch[cx][cy]=0;
 
  while(true){
    t=Q[s++];
    num--;
    cx=t.x,cy=t.y,cost=t.cost;
    ch=t.ch;
 
    rep(i,4){
      nx=cx+dx[i],ny=cy+dy[i];
      if(nx<0 || nx>=h || ny<0 || ny>=w)continue;
      if(ku[nx][ny]=='X')continue;
      nch=ch;
      if(ku[nx][ny]<='9' && ku[nx][ny]>='1' && ku[nx][ny]-'0'==t.ch+1){
        nch=ch+1;
      }
 
      if(maxch[nx][ny]>=nch)continue;
      if(nch==n){
        printf("%d\n",cost+1);
        return 0;
      }
      maxch[nx][ny]=nch;
      Q[s+num++]=(mouse){nx,ny,cost+1,nch};
    }
  }
}

C++: #include <cstdio>
#include <iostream>
#include <queue>
#include <tuple>

#define MAX_W 1010
#define MAX_H 1010

using namespace std;

int w, h, n;
char sections[MAX_H][MAX_W];
bool visited[MAX_H][MAX_W];
int dx[] = {1, 0, -1, 0};
int dy[] = {0, -1, 0, 1};


int main() {
  scanf("%d %d %d", &h, &w, &n);
  for (int i = 0; i < h; ++i) {
    scanf("%s", sections[i]);
  }

  int sx, sy;
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      if (sections[i][j] == 'S') {
        sx = j; sy = i;
      }
    }
  }

  int ans = 0;
  queue<tuple<int, int, int> > que;
  que.push(make_tuple(sx, sy, 0));
  for (int hp = 1; hp <= n; ++hp) {
    for (int i = 0; i < h; ++i) {
      for (int j = 0; j < w; ++j) {
        visited[i][j] = false;
      }
    }

    tuple<int, int, int> res;
    while (!que.empty()) {
      int x, y, d;
      tie(x, y, d) = que.front(); que.pop();
      visited[y][x] = true;
      for (int i = 0; i < 4; ++i) {
        int nx = x + dx[i], ny = y + dy[i];
        if ((0 <= nx && nx < w && 0 <= ny && ny < h) &&
            (!visited[ny][nx] && sections[ny][nx] != 'X')) {
          if (sections[ny][nx] == ('0' + hp))
            res = make_tuple(nx, ny, d + 1);
          else {
            visited[ny][nx] = true;
            que.push(make_tuple(nx, ny, d + 1));
          }
        }
      }
    }

    int x, y, d;
    tie(x, y, d) = res;
    ans += d;
    que = queue<tuple<int, int, int> >();
    que.push(make_tuple(x, y, 0));
  }
  printf("%d\n", ans);
  
  return 0;
}