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<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 tim[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])
			{
				tim[next.x][next.y] = tim[now.x][now.y] + 1;
				q.push(next);
			}
		}
	}
	return tim[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')
				tim[i][j] = INF;
		}
	}
	tim[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]);
				tim[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;
		tim[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 <stdio.h>
#include <queue>

#define MAP_SIZE_MAX 1001
#define INF 100000000

typedef std::pair<int, int> point;

int get_distance(int sx, int sy, int goal,
                 int h, int w, char map[][MAP_SIZE_MAX]) {
  std::queue<point> queue;
  queue.push(point(sx, sy));

  // initalize distance array
  int distance[MAP_SIZE_MAX][MAP_SIZE_MAX];
  for (int i = 0; i < MAP_SIZE_MAX; i++) {
    for (int j = 0; j < MAP_SIZE_MAX; j++) {
      distance[i][j] = INF;
    }
  }
  distance[sx][sy] = 0;

  // ???????????¢?´¢
  while (true) {
    point current = queue.front();
    queue.pop();
    int x = current.first;
    int y = current.second;

    // goal!
    if (map[x][y] == goal + '0') {
      return distance[x][y];
    }

    // 4 ???????????????
    int d[] = { 0, 1, 0, -1, 0 };
    for (int i = 0; i < 4; i++) {
      int _x = x + d[i];
      int _y = y + d[i + 1];
      if (map[_x][_y] != 'X' &&
          distance[_x][_y] == INF &&
          0 <= _x && _x < h && 0 <= _y && _y < w) {
        distance[_x][_y] = distance[x][y] + 1;
        queue.push(point(_x, _y));
      }
    }
  }
}

int solve(int h, int w, int n, char map[][MAP_SIZE_MAX]) {
  // find start position
  int sx, sy, gx, gy;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (map[i][j] == 'S') {
        sx = i;
        sy = j;
        break;
      }
    }
  }

  int result = 0;
  for (int i = 1; i <= n; i++) {
    result += get_distance(sx, sy, i, h, w, map);

    // ??´????????????????¬??????????????????????
    sx = gx;
    sy = gy;
  }

  return result;
}

int main() {
  int h, w, n;
  scanf("%d %d %d", &h, &w, &n);

  char map[MAP_SIZE_MAX][MAP_SIZE_MAX];
  for (int i = 0; i < h; i++) {
    scanf("%s", map[i]);
  }

  printf("%d\n", solve(h, w, n, map));

  return 0;
}

C++: #include <iostream>
#include <utility>
#include <queue>
#include <algorithm>
using namespace std;

bool ary[1010][1010];
bool sag[1010][1010];
int goalx[11],goaly[11];
int main(){
	queue<pair<pair<int,int>,int>> qu;
	pair<pair<int,int>,int> pa;
	int H,W,N,YY,XX,TT,keka;
	char ch;
	keka=0;
	cin>>H>>W>>N;
	for(int i=0;i<H;i++){
		for(int j=0;j<W;j++){
			cin>>ch;
			if(ch>='1'&&ch<='9'){
				goaly[ch-'0']=i;
				goalx[ch-'0']=j;
			}
			if(ch=='S'){
				goaly[0]=i;
				goalx[0]=j;
			}
			ary[i][j]=(ch=='X');
		}
	}

	for(int sta=0;sta<N;sta++){
		for(int i=0;i<H;i++){
			for(int j=0;j<W;j++){
				sag[i][j]=false;
			}
		}
		qu.push(make_pair(make_pair(goaly[sta],goalx[sta]),0));
		while(!qu.empty()){
			pa=qu.front();
			qu.pop();
			YY=pa.first.first;
			XX=pa.first.second;
			TT=pa.second;
			if(YY==goaly[sta+1]&&XX==goalx[sta+1]){
				//cout<<sta<<" "<<TT<<endl;//
				keka+=TT;
				while(!qu.empty())qu.pop();
				break;
			}

			if(YY>0&&!ary[YY-1][XX]&&!sag[YY-1][XX]){
				qu.push(make_pair(make_pair(YY-1,XX),TT+1));
				sag[YY-1][XX]=true;
			}
			if(YY<H-1&&!ary[YY+1][XX]&&!sag[YY+1][XX]){
				qu.push(make_pair(make_pair(YY+1,XX),TT+1));
				sag[YY+1][XX]=true;
			}
			if(XX>0&&!ary[YY][XX-1]&&!sag[YY][XX-1]){
				qu.push(make_pair(make_pair(YY,XX-1),TT+1));
				sag[YY][XX-1]=true;
			}
			if(XX<W-1&&!ary[YY][XX+1]&&!sag[YY][XX+1]){
				qu.push(make_pair(make_pair(YY,XX+1),TT+1));
				sag[YY][XX+1]=true;
			}
		}
	}
	cout<<keka<<endl;
	return 0;
}

C++: #include<iostream>
#include<queue>
using namespace std;
struct Point{int x,y,dist;};
int main()
{
  int H,W,N;
  char vital='1';
  int i,j;
  string field[1000];
  bool visited[1000][1000];
  queue<Point>q;
  int dx[4]={0,1,0,-1};
  int dy[4]={-1,0,1,0};
  Point ans;

  cin>>H>>W>>N;
  for(i=0;i<H;i++)cin>>field[i];
  for(i=0;i<H;i++){
    for(j=0;j<W;j++){
      if(field[i][j]=='S'){
	Point p={j,i,1};
	q.push(p);
      }
    }
  }
  for(i=0;i<H;i++)for(j=0;j<W;j++)visited[i][j]=false;

  while(q.size()){
    Point p=q.front();
    q.pop();
    visited[p.y][p.x]=true;
    for(i=0;i<4;i++){
      Point p2;
      p2.y=p.y+dy[i];
      p2.x=p.x+dx[i];
      p2.dist=p.dist+1;
      if(p2.y<0||H<=p2.y)continue;
      if(p2.x<0||W<=p2.x)continue;
      if(field[p2.y][p2.x]=='X')continue;
      if(visited[p2.y][p2.x])continue;
      if(field[p2.y][p2.x]==vital){
	vital++;
	while(q.size())q.pop();
	for(i=0;i<H;i++)for(j=0;j<W;j++)visited[i][j]=false;
	if(vital-'0'==N+1){
	  ans=p;
	  break;
	}
      }
      q.push(p2);
    }
  }
  cout<<ans.dist<<endl;
}