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

const int MAX_H = 1005;
const int MAX_W = 1005;

string all[MAX_H];
int dx[4] = { 1, 0, -1, 0 };
int dy[4] = { 0, 1, 0, -1 };
int h, w;
int n;
int sx, sy;
typedef pair<int ,int> P;

int bfs(char target){
	set<P> s;
	queue<P> q1;
	queue<int> q2;
	q1.push(P(sy, sx));
	s.insert(P(sy, sx));
	q2.push(0);
	while (!q1.empty()){
		P p = q1.front(); q1.pop();
		int t = q2.front(); q2.pop();
		cout << p.first << " " << p.second <<" "<<t<< endl;
		for (int i = 0; i < 4; ++i){
			int y = p.first + dy[i], x = p.second + dx[i];
			if (x >= 0 && x < w &&y >= 0 && y < h && all[y][x] != 'X'){
				if (s.count(P(y,x))){
					continue;
				}
				if (all[y][x] == target){
					all[y][x] = '.';
					sx = x, sy = y;
					return t + 1;
				}
				else{
					q1.push(P(y, x));
					q2.push(t + 1);
					s.insert(P(y, x));
				}
			}
		}
	}
}

void solve(){
	int ans = 0;
	char t = '1';
	for (int i = 0; i < n;++i){
		ans += bfs(t);
		++t;
	}
	cout << ans << endl;
}

int main(){
	cin >> h >> w >> n;
	for (int i = 0; i < h; ++i){
		cin >> all[i];
		for (int j = 0; j < w; ++j){
			if (all[i][j] == 'S'){
				sx = j, sy = i;
				all[i][j] = '.';
			}
		}
	}
	solve();
	return 0;
}

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

typedef tuple<int, int, int> T;
int X, Y, N;
char mat[1001][1001];
int sx[10];
int sy[10];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

int bfs(int x, int y, int n) {
    auto Q = queue<T>();
    Q.push(make_tuple(x, y, 0));
    int t;
    while (!Q.empty()) {
        tie(x, y, t) = Q.front(); Q.pop();
        if (x == sx[n+1] && y == sy[n+1]) {
            return t;
        }
        for (int i=0; i<4; ++i) {
            int xx = x + dx[i];
            int yy = y + dy[i];
            if (0 <= xx && xx < X && 0 <= yy && yy < Y && mat[xx][yy] != 'X' && mat[xx][yy] != '0' + n) {
                mat[xx][yy] = '0' + n;
                Q.push(make_tuple(xx, yy, t+1));
            }
        }
    }
    return -1;
}

int main() {
    cin >> X >> Y >> N;

    for (int i=0; i<X; ++i) {
        for (int j=0; j<Y; ++j) {
            cin >> mat[i][j];
            if (mat[i][j] == 'S') {
                sx[0] = i, sy[0] = j;
            }
            if ('1' <= mat[i][j] && mat[i][j] <= '9') {
                sx[mat[i][j] - '0'] = i; 
                sy[mat[i][j] - '0'] = j; 
            }
        }
    }
    
    int res = 0;
    for (int i=0; i<N; ++i) {
        res += bfs(sx[i], sy[i], i);
    }
    cout << res << endl;
    return 0;
}

C++: /*
Hokudai Practice Contest 2014
D - Cheese

ティツァツ」テヲツウツ陛ッツシツ咤FS
テ」ツδ?」ツδシテ」ツつコテ」ツつ?テ」ツ?、テゥツ」ツ淌」ツ?ケテァツオツづ」ツつ湘」ツ?」テ」ツ?ヲテ」ツ?凝」ツつ嘉ヲツャツ。テ」ツ?ォテ・ツ青妥」ツ?凝」ツ??」ツδ?」ツδシテ」ツつコテ」ツ?ョテ、ツスツ催ァツスツョテ」ツ?古・ツョツ堙」ツつ?」ツつ嘉」ツつ古」ツ?ヲテ」ツ??」ツつ凝」ツ?ョテ」ツ?ァテ」ツ??
(S -> 1テ」ツ?ョテヲツ慊?ァツ淞ュティツキツッ) + (1 -> 2テ」ツ?ョテヲツ慊?ァツ淞ュティツキツッ) + ... + (N-1 -> Nテ」ツ?ョテヲツ慊?ァツ淞ュティツキツッ)テ」ツつ津ヲツアツづ」ツつ?」ツつ古」ツ?ーティツ可ッテ」ツ??」ツ??
テヲツ慊?ァツ淞ュティツキツッテ」ツ?ョティツィツ暗ァツョツ療」ツ?ォテ」ツ?ッBFS(テ・ツケツ?・ツ?ェテ・ツ?暗ヲツ篠「テァツエツ「)テ」ツつ津ァツ板ィテ」ツ??」ツつ凝」ツ?禿」ツ?ィテ」ツ?古」ツ?ァテ」ツ?催」ツつ凝」ツ??

BFSテ、ツクツ?・ツ崢榲」ツ?ョテヲツ卍づゥツ鳴禿ィツィツ暗ァツョツ療ゥツ?湘」ツ?薫(HW)テ」ツ?ァテ」ツ??」ツ?禿」ツつ古」ツつ誰テ・ツ崢榲ィツ。ツ古」ツ??」ツ?ョテ」ツ?ァテ」ツ??・ツ?ィテ、ツスツ禿」ツ?ァO(NHW)テ」ツ?ィテ」ツ?ェテ」ツつ凝」ツ??
*/

#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;

//テゥツ堋」テヲツ篠・4テヲツ鳴ケテ・ツ青妥」ツつ津・ツョツ堙ァツセツゥ
const int dy[] = {-1,0,1,0}, dx[] = {0,1,0,-1};
const int INF = 1e8;

int main(){
  int h,w,n;
  int x[10],y[10];
  string grid[1000];
  cin >> h >> w >> n;

  for(int i=0;i<h;i++)cin >> grid[i];

  //テ」ツδ?」ツδシテ」ツつコiテ」ツ?ョテ・ツ?エテヲツ可?」ツつ遅[i],y[i]テ」ツ?ォティツィツ佚ゥツ個イ
  for(int i=0;i<h;i++){
    for(int j=0;j<w;j++){
      if(grid[i][j] == 'S'){
	y[0] = i; x[0] = j;
      }
      if(grid[i][j] != 'X' && grid[i][j] != '.'){
	y[grid[i][j] - '0'] = i; x[grid[i][j] - '0'] = j;
      }
    }
  }

  int ans = 0;
  //nテ・ツ崢曖FSテ」ツつ津ィツ。ツ古」ツ??
  for(int i=0;i<n;i++){
    int dis[1000][1000];
    queue<int> qx,qy;

    //テ・ツ按敕ヲツ慊淌・ツ個?
    for(int k=0;k<h;k++){
      for(int j=0;j<w;j++){
	dis[k][j] = INF;
      }
    }
    dis[y[i]][x[i]] = 0;

    qy.push(y[i]); qx.push(x[i]);

    //BFS
    while(!qx.empty()){
      //テァツ渉セテ・ツ慊ィテ」ツ?ョテ、ツスツ催ァツスツョ
      int cy = qy.front(), cx = qx.front();
      qy.pop(); qx.pop();

      //テゥツ堋」テヲツ篠・4テヲツ鳴ケテ・ツ青妥」ツつ津ヲツ篠「テァツエツ「テ」ツ?凖」ツつ?
      for(int d=0;d<4;d++){
	int ny = cy + dy[d], nx = cx + dx[d];
	//テァツ崢、テ・ツ、ツ姪・ツ按、テ・ツョツ?
	if(ny<0 || nx<0 || ny>=h || nx>=w)continue;
	//テゥツ堋愿・ツョツウテァツ可ゥテ・ツ按、テ・ツョツ?
	if(grid[ny][nx] == 'X')continue;

	//dis == INFテ」ツ?ェテ」ツつ嘉」ツ??」ツ?セテ」ツ??ィツィツェテ」ツつ古」ツ?ヲテ」ツ??」ツ?ェテ」ツ??
	if(dis[ny][nx] == INF){
	  dis[ny][nx] = dis[cy][cx] + 1;
	  qy.push(ny); qx.push(nx);
	}
      }
    }

    ans += dis[y[i+1]][x[i+1]];
  }

  cout << ans << endl;
}

C++: #include <iostream>
#include <string>
#include <cstring>
#include <queue>

using namespace std;

typedef pair<int,int> pint;
const int dx[]={1,0,-1,0};
const int dy[]={0,1,0,-1};
string mp[1000];
int visit[1000][1000];

int main(){
    int h,w,n,cx,cy,ans=0;
    cin>>h>>w>>n;
    for(int i=0;i<h;++i){
        cin>>mp[i];
        if(mp[i].find('S')!=string::npos){
            cy=i;cx=mp[i].find('S');
        }
    }    
    for(int i=1;i<=n;++i){
        memset(visit,0,sizeof(visit));
        visit[cy][cx]=1;
        queue<pint> q;
        q.push(make_pair(cx,cy));
        while(!q.empty()){
            pint pi=q.front();q.pop();
            cx=pi.first;cy=pi.second;
            int vc=visit[cy][cx];
            if(mp[cy][cx]==i+'0'){
                ans+=vc-1;break;
            }
            for(int j=0;j<4;++j){
                int tx=cx+dx[j];int ty=cy+dy[j];
                if(tx>=0&&ty>=0&&tx<w&&ty<h&&visit[ty][tx]==0&&mp[ty][tx]!='X'){
                    q.push(make_pair(tx,ty));
                    visit[ty][tx]=vc+1;
                }
            }
        }
    }
    cout<<ans<<endl;
    return 0;
}