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<queue>
#include<cctype>
#include<cstdio>

#define	mp			make_pair
#define	rep(i,n)	for(int i=0;i<n;i++)

using namespace std;

typedef	pair<int,int>	pii;

const int dx[]={1,0,-1,0},dy[]={0,-1,0,1};

int h,w;
char grid[1000][1001];

int shortestDistance(int sx,int sy,int gx,int gy){
	static bool visited[1000][1000];
	rep(i,h)rep(j,w)	visited[i][j]=false;
	visited[sy][sx]=true;

	queue< pair<int,pii> > qu;	qu.push(mp(0,mp(sy,sx)));
	while(1){
		pair<int,pii> a=qu.front();	qu.pop();
		int d=a.first,x=a.second.second,y=a.second.first;
		if(x==gx && y==gy)	return d;

		rep(i,4){
			int xx=x+dx[i],yy=y+dy[i];
			if(0<=xx && xx<w && 0<=yy && yy<h && grid[yy][xx]!='X' && !visited[yy][xx]){
				visited[yy][xx]=true;
				qu.push(mp(d+1,mp(yy,xx)));
			}
		}
	}
}

int main(){
	int n;	scanf("%d%d%d",&h,&w,&n);
	int cx[10],cy[10];
	rep(i,h){
		scanf("%s",grid[i]);
		rep(j,w){
			if(grid[i][j]=='S')		cx[0]=j,cy[0]=i;
			if(isdigit(grid[i][j]))	cx[grid[i][j]-'0']=j,cy[grid[i][j]-'0']=i;
		}
	}

	int cost=0;
	rep(i,n)	cost+=shortestDistance(cx[i],cy[i],cx[i+1],cy[i+1]);
	printf("%d\n",cost);

	return 0;
}

C++: #include <iostream>
#include <fstream>
#include <typeinfo>
#include <vector>
#include <stack>
#include <cmath>
#include <set>
#include <map>
#include <string>
#include <algorithm>
#include <cstdio>
#include <queue>
#include <iomanip>
#include <cctype>
#define syosu(x) fixed<<setprecision(x)
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
typedef pair<double,double> pdd;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<char> vc;
typedef vector<vc> vvc;
typedef vector<string> vs;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef vector<P> vp;
typedef vector<vp> vvp;
typedef pair<int,P> pip;
typedef vector<pip> vip;
const int inf=1<<28;
const ll INF=1ll<<50;
const double pi=acos(-1);
const double eps=1e-10;
const ll mod=1e9+7;
const vi emp;
const int dx[4]={0,1,0,-1},dy[4]={1,0,-1,-0};
const int DX[8]={-1,-1,-1,0,0,1,1,1},DY[8]={1,0,-1,1,-1,1,0,-1};

int h,w,n;
vvc a;

int main(){
	cin>>h>>w>>n;
	a=vvc(h,vc(w));
	vp b(n+1);
	for(int i=0;i<h;i++) for(int j=0;j<w;j++){
		cin>>a[i][j];
		if(a[i][j]=='S') b[0]=P(i,j);
		else if(a[i][j]!='.'&&a[i][j]!='X') b[a[i][j]-'0']=P(i,j);
	}
	int ans=0;
	for(int i=0;i<n;i++){
		vvc c=a;
		queue<pip> q;
		q.push(pip(0,b[i]));
		while(!q.empty()){
			pip p=q.front();
			q.pop();
			P r=p.second;
			bool flag=0;
			for(int j=0;j<4;j++){
				int cx=r.first+dx[j],cy=r.second+dy[j];
				if(cx>=0&&cx<h&&cy>=0&&cy<w&&c[cx][cy]!='X'){
					if(c[cx][cy]==(char)(i+1)+'0'){
						ans+=p.first+1;
						flag=1;
						break;
					}
					c[cx][cy]='X';
					q.push(pip(p.first+1,P(cx,cy)));
				}
			}
			if(flag) break;
		}
	}
	cout<<ans<<endl;
}

C++: #include<iostream>
#include<queue>
using namespace std;
struct Data{
    int x;
    int y;
    int t;
    int c;
};
bool vis[1005][1005][10];
const int dx[] = {1,0,-1,0},dy[] = {0,1,0,-1};
int main(){
    int h,w,n;
    cin>>h>>w>>n;
    string fi[1020];
    Data init;
    for(int i = 0;i < h;i++){
        cin>>fi[i];
        for(int j = 0;j < w;j++){
            if(fi[i][j] == 'S'){
                init.x = j;
                init.y = i;
            }
        }
    }
    init.t = 0;
    init.c = 1;

    queue<Data> Q;
    Q.push(init);

    while(!Q.empty()){
        Data D = Q.front();
        Q.pop();
        D.t++;
        vis[D.y][D.x][D.c] = true;
        if(fi[D.y][D.x] == D.c + '0')D.c++;
        if(D.c == n+1){
            cout<<D.t-1<<endl;
            return 0;
        }
        for(int i = 0;i < 4;i++){
            int x = D.x + dx[i];
            int y = D.y + dy[i];
            if(0 <= x&&x < w&&0 <= y&& y < h){
                if(fi[y][x] == 'X')continue;
                if(vis[y][x][D.c])continue;
                Data E = D;
                E.x = x, E.y = y;
                Q.push(E);
            }
        }
    }
}

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

int h, w, n;

int p[10][2];

int dx[] = { 1, 0, -1, 0};
int dy[] = { 0, 1, 0, -1};

bool a[1000][1000];
int m[1000][1000];

char str[1001];

int t(int sx, int sy, int ex, int ey) {
	for (int i=0;i<h;i++) {
		for(int j=0;j<w;j++) {
			m[j][i] = -1;
		}
	}
	m[sx][sy] = 0;
	
	queue< pair<int, int> > que;
	que.push( make_pair(sx, sy) );
	
	while(!que.empty()) {
		 pair<int, int> np = que.front();
		que.pop();
		for(int i=0;i<4;i++) {
			int px = np.first+dx[i], py = np.second+dy[i];
			if( (px<0||px>=w) || (py<0||py>=h) )continue;
			else if( !a[px][py] )continue;
			else if(px==ex&&py==ey)return m[np.first][np.second]+1;
			else if( m[px][py]>=0 && m[px][py]<=(m[np.first][np.second]+1) )continue;
			m[px][py] = m[np.first][np.second]+1;
			que.push( make_pair(px, py) );
		}
	}
	
	cout << "error!" << endl;
	return -1;
}

int main() {
	
	cin >> h >> w >> n;
	
	for(int i=0;i<h;i++) {
		cin >> str;
		for(int j=0;j<w;j++) {
			a[j][i] = (str[j]!='X');
			if(str[j]=='S') {
				p[0][0] = j;
				p[0][1] = i;
			}else if(str[j]>='1' && str[j]<='9') {
				p[str[j] - '0'][0] = j;
				p[str[j] - '0'][1] = i;
			}
		}
	}
	
	int s = 0;
	for(int i=0;i<n;i++) {
		s += t(p[i][0], p[i][1], p[i+1][0],  p[i+1][1]);
	}
	
	cout << s << endl;
	
	return 0;
}

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


int main()
{
  int h,w,n;
  cin>>h>>w>>n;
  char map[h][w];
  bool closed[h][w];
  int sx,sy;
  for(int i=0;i<h;i++)
    for(int j=0;j<w;j++)
      {
	cin>>map[i][j];
	if(map[i][j]=='S')
	  {
	    sx=i;
	    sy=j;
	  }
      }
  int ans=0;
  int dx[]={1,-1,0,0};
  int dy[]={0,0,-1,1};
  for(int i=1;i<=n;i++)
    {
      queue<pair<pair<int,int>,int> >qu;
      while(!qu.empty())
	qu.pop();
      qu.push(make_pair(make_pair(sx,sy),0));
      memset(closed,false,sizeof(closed));
      while(true)
	{
	  pair<pair<int,int> ,int> tmp=qu.front();
	  qu.pop();
	  int x=tmp.first.first;
	  int y=tmp.first.second;
	  int step=tmp.second;
	  //	  cout<<x<<" "<<y<<" "<<step<<endl;
	  if(map[x][y]=='0'+i)
	    {
	      ans+=step;
	      //cout<<"fin :"<<i<<" step;"<<step<<endl;
	      sx=x;
	      sy=y;
	      break;
	    }
	  if(closed[x][y])
	    continue;
	  closed[x][y]=true;
	  for(int xx=0;xx<4;xx++)
	    {
	      if(x+dx[xx]>=0 && x+dx[xx]<h &&
		 y+dy[xx]>=0 && y+dy[xx]<w &&
		 !closed[x+dx[xx]][y+dy[xx]] &&
		 map[x+dx[xx]][y+dy[xx]]!='X'
		 )
		qu.push(make_pair(make_pair(x+dx[xx],y+dy[xx]),step+1));
	    }
	}
    }
  cout<<ans<<endl;
}