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<vector>
#include<algorithm>

using namespace std;

const int MAX = 1001;
const int INF = (1<<20);
typedef pair<int,int> P;
typedef pair<int,P> PP;

int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};
char grid[MAX][MAX];
int cost[MAX][MAX];
int H,W,N;
vector<PP> V;
P f,t;

void init(){
  for(int i = 0; i <= H; i++)
    for(int j = 0; j <= W; j++)
      cost[i][j] = INF;

}

void input(){
  for(int i = 1; i <= H; i++)
    for(int j = 1; j <= W; j++){
      cin >> grid[i][j];
      PP pp;

      if(grid[i][j] == 'S' || '0' <= grid[i][j] && grid[i][j] <= '9'){
	if(grid[i][j] == 'S') pp.first = 0;
	else pp.first = grid[i][j] - '0';
	
	pp.second = P(i,j);
	V.push_back(pp);
      }
    }
}


bool isIn(P p){
  return 0 < p.first && p.first<= H && 0 < p.second && p.second <= W;
}
void solve(P p){

  int n = cost[p.first][p.second];

  for(int i = 0; i < 4; i++){
    P next = p;
    next.first += dy[i];
    next.second += dx[i];
    if(grid[next.first][next.second] != 'X' && cost[next.first][next.second] > n+1 && isIn(next)){
	cost[next.first][next.second] = n+1;
	if(next != t) solve(next);
    }
  }
}

P find(int n){
  for(int i = 0; i < V.size(); i++)
    if(V[i].first == n) return V[i].second;

}

int main(){

  cin >> H >> W >> N;

  input();
  sort(V.begin(),V.end());
  
  int ans = 0;
 
  for(int i = 1; i <= N; i++){
    init();
    f = find(i-1), t = find(i);
    cost[f.first][f.second] = 0;
    solve(f);
    ans += cost[t.first][t.second];
    
  }
  cout << ans << endl;
  return 0;
}

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

class P{
public:
	int x,y,cost;

	P(int _x,int _y,int _cost){
		x = _x;
		y = _y;
		cost = _cost;
	}
};

int h,w,n;
char t[1002][1002];
bool closed[1002][1002];
int dx[] = {-1,0,1,0};
int dy[] = {0,1,0,-1};

P minDist(int x,int y,char to){
	queue<P> open;
	memset(closed,0,sizeof(closed));

	open.push(P(x,y,0));

	while(!open.empty()){
		P p = open.front(); open.pop();
		if(closed[p.x][p.y]) continue;
		closed[p.x][p.y] = true;

		if(t[p.y][p.x] == to){
			return p;
		}

		for(int i=0;i<4;i++){
			int nx = p.x + dx[i];
			int ny = p.y + dy[i];

			if(nx>=0 && nx<w && ny>=0 && ny<h && t[ny][nx]!='X'){
				open.push(P(nx,ny,p.cost+1));
			}
		}
	}
}

int main(void){
	cin>>h>>w>>n;

	int x,y;
	for(int i=0;i<h;i++){
		cin>>t[i];
		for(int j=0;j<w;j++){
			if(t[i][j] == 'S'){
				t[i][j] = '.';
				x = j;
				y = i;
			}
		}
	}

	int ans = 0;
	for(int i=1;i<=n;i++){
		P res = minDist(x,y,'0'+i);
		ans += res.cost;
		x = res.x;
		y = res.y;
	}
	cout<<ans<<endl;

	return 0;
}

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

struct DAT{
  int x;
  int y;
  int total;
};

int main(void){
  int h,w,n;
  cin>>h>>w>>n;
  vector<string> field(h);
  map<int,pair<int,int> > ps;
  for(int i=0;i<h;++i){
    int j;
    cin>>field[i];
    if((j = field[i].find('S')) != string::npos)
      ps[0] = make_pair(j,i);
    for(char c='1';c<='9';++c)
      if((j = field[i].find(c)) != string::npos)
        ps[c-'0'] = make_pair(j,i);
  }
  int ans=0;
  for(int i=0;i<n;++i){
    int sx = ps[i].first, sy = ps[i].second;
    vector<vector<int> > dist(h);
    for(int j=0;j<h;++j){
    	dist[j]=vector<int>(w);
    	for(int k=0;k<w;++k){
    		dist[j][k]=1e9;
    	}
    }
    queue<DAT> Q;
    DAT start;
    start.x = sx; start.y = sy; start.total = 0;
    Q.push(start);
    int sum = 0;
    while(!Q.empty()){
      DAT dat = Q.front();Q.pop();
      if(dist[dat.y][dat.x]<dat.total) continue;
      if(dat.x == ps[i+1].first && dat.y == ps[i+1].second){sum=dat.total;break;}
      if(field[dat.y][dat.x] == '.' || field[dat.y][dat.x] == 'S' || ('1'<=field[dat.y][dat.x] && field[dat.y][dat.x] <= '9')){
        dist[dat.y][dat.x] = dat.total;
        if(dat.x>0){
          DAT nxt;
          nxt.x=dat.x-1;nxt.y=dat.y;nxt.total=dat.total+1;
          Q.push(nxt);
        }
        if(dat.y>0){
          DAT nxt;
          nxt.x=dat.x;nxt.y=dat.y-1;nxt.total=dat.total+1;
          Q.push(nxt);
        }
        if(dat.x<w-1){
          DAT nxt;
          nxt.x=dat.x+1;nxt.y=dat.y;nxt.total=dat.total+1;
          Q.push(nxt);
        }
        if(dat.y<h-1){
          DAT nxt;
          nxt.x=dat.x;nxt.y=dat.y+1;nxt.total=dat.total+1;
          Q.push(nxt);
        }
      }
    }
    ans+=sum;
  }
  cout<<ans<<endl;
  return 0;
}

C++: //0558 ?????????
//bfs

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<functional>
#include<iostream>
#include<queue>
#define INF 2100000000
using namespace std;
typedef pair<int,int> P;
int glid[1001][1001];
char put[1001][1001];
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};
char su[9]={'1','2','3','4','5','6','7','8','9'};
int main(void)
{
	int i,j,k,h,w,n,sum,x,y;
	int sx,sy;
	P pop_xy;
	queue<P> push_xy;
	cin>>h>>w>>n;
	for(i=0;i<h;i++) cin>>put[i];
	for(i=0;i<h;i++) {
		for(j=0;j<w;j++) {
			glid[i][j]=INF;
		}
	}		
	for(i=0;i<h;i++) {
		for(j=0;j<w;j++) {
			if(put[i][j]=='S') {
				push_xy.push(P(i,j));
				glid[i][j]=0;
				break;
			}
		}
	}
	sum=0;
	for(i=0;i<n;i++) {
		if(i>0) {
			for(j=0;j<h;j++) {
				for(k=0;k<w;k++) glid[j][k]=INF;
			}		
			while(push_xy.size()!=0) push_xy.pop();
			push_xy.push(P(sy,sx));
			glid[sy][sx]=0;
		}
		while(push_xy.size()!=0) {
			pop_xy=push_xy.front();push_xy.pop();
			if(put[pop_xy.first][pop_xy.second]==su[i]) {
				sum+=glid[pop_xy.first][pop_xy.second];
				sy=pop_xy.first;sx=pop_xy.second;
				break;
			}
			for(j=0;j<4;j++) {
				y=dy[j]+pop_xy.first;
				x=dx[j]+pop_xy.second;
				if(y>=0 && y<h && x>=0 && x<w &&
				put[y][x]!='X' && glid[y][x]==INF) {
					push_xy.push(P(y,x));
					glid[y][x]=glid[pop_xy.first][pop_xy.second]+1;
				}
			}
		}
	}
	cout<<sum<<endl;
	return 0;
}

C++: #include<iostream>
#include<queue>
using namespace std;
struct Point{int x,y,dist;};
int main()
{
  int H,W,N;
  int vital;
  int i,j;
  string field[1000];
  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'){
	ans.y=i;
	ans.x=j;
	ans.dist=0;
      }
    }
  }

  for(vital=1;vital<=N;vital++){
    queue<Point>q;
    bool visited[1000][1000]={0};
    bool f=0;

    q.push(ans);
    while(!f){
      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+'0'){
	  ans=p2;
	  f=1;
	  break;
	}
	q.push(p2);
      }
    }
  }
  cout<<ans.dist<<endl;
}