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<deque>

using namespace std;

int H, W, N;
char mapT[1000][1000];
int vis[1000][1000];
int temp_x = 0, temp_y;
char temp;
int final_min_route = 0;
int dir[4][2] = { {-1,0},{0,1},{1,0},{0,-1} };

struct location {
	int x, y, route;
};

location findSmallRouteBFS(int x, int y, char factory) {
	memset(vis, 0, sizeof(vis));
	deque<location> que;
	location temp = { x,y,0 };
	que.push_back(temp);
	vis[x][y] = 1;
	while (!que.empty()) {
		location st = que.front();
		que.pop_front();
		if (mapT[st.x][st.y] == factory) {
			return st;
		}
		for (int i = 0; i < 4; ++i) {
			int t_x = st.x + dir[i][0];
			int t_y = st.y + dir[i][1];
			if (t_x < 0 || t_x >= H || t_y < 0 || t_y >= W || mapT[t_x][t_y] == 'X') {
				continue;
			}
			location temp = { t_x,t_y,st.route + 1 };
			if (!vis[t_x][t_y]) {
				vis[t_x][t_y] = 1;
				que.push_back(temp);
			}
		}
	}

}

int main() {
	cin >> H >> W >> N;
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; ++j) {
			cin >> temp;
			mapT[i][j] = temp;
			if (temp == 'S') {
				mapT[i][j] = '0';
				temp_x = i;
				temp_y = j;
			}
		}
	}

	for (int factory = 1; factory != N + 1; ++factory) {

		location lo = findSmallRouteBFS(temp_x, temp_y, mapT[temp_x][temp_y] + 1);
		temp_x = lo.x;
		temp_y = lo.y;
		final_min_route += lo.route;
	}

	cout << final_min_route << endl;
	//system("pause");
	return 0;
}

C++: // No.3

#include<iostream>
#include<map>
#include<queue>

#define INF 10000
using namespace std;

typedef pair<int ,int> P;

char map_data[1001][1001];
int data[1001][1001];
int W,H;

int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
int bfs (P s,P g){
	fill((int*) data,(int*)(data +1001),INF);
	data[s.first][s.second]=0;
	queue<P> que;

	que.push(s);
	while(que.size()){
		P p=que.front();que.pop();
		
		for(int i=0;i<4;i++){
			int nx=p.second+dx[i],ny=p.first+dy[i];
			if(0<=nx && nx<W && 0<=ny && ny<H && map_data[ny][nx]!='X' && data[p.first][p.second]+1<data[ny][nx]){
				que.push(P(ny,nx));
				data[ny][nx]=data[p.first][p.second]+1;
				
			}

		}

	}
return data[g.first][g.second];	
}

int main(){
int n;
cin>>H>>W>>n;

P ar[10];

for(int i=0;i<H;i++){
	for(int j=0;j<W;j++){
	cin>>map_data[i][j];
	if(map_data[i][j]!='.' && map_data[i][j]!='X'){
		if(map_data[i][j]=='S')ar[0]=P(i,j);
		else{
		ar[map_data[i][j]-'0']=P(i,j);
		}
	}
	}
}
int ans=0;
for(int i=0;i<n;i++){
ans+=bfs(ar[i],ar[i+1]);
}

cout<<ans<<endl;
}

C++: #include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<map>
#include<queue>
#include<algorithm>

using namespace std;
const int INF=100000000;

typedef pair<int, int> P;

int h,w,n;
int ans=0;
int sx,sy;
int kx[10],ky[10];
long int field[1001][1001],field2[1001][1001];
char str[1001];
int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1,};

int bfs(int x,int y,int e){
	int a=0,b=0;
	queue<P> que;
	for(a=0;a<h;a++){
		for(b=0;b<w;b++){
			field2[b][a]=INF;
		}
	}
	que.push(P(x,y));
	field2[x][y]=0;
	while(que.size()){
		P p=que.front();que.pop();
		if(p.first==kx[e] && p.second==ky[e])break;
		for(a=0;a<4;a++){
			int nx=p.first+dx[a],ny=p.second+dy[a];
			if(0<=nx && nx<w && 0<=ny && ny<h && field[nx][ny]!=-1 && field2[nx][ny]==INF){
				que.push(P(nx,ny));
				field2[nx][ny]=field2[p.first][p.second]+1;
			}
		}
	}
	return field2[kx[e]][ky[e]];
}

int main(void){
	int a,b;
	scanf("%d %d %d",&h,&w,&n);
	for(a=0;a<h;a++){
		scanf("%s",str);
		for(b=0;b<w;b++){
			if(str[b]=='S')sx=b,sy=a;
			if(str[b]=='X')field[b][a]=-1;
			else field[b][a]=0;
			if('1' <= str[b] && str[b] <= '9'){
				field[b][a]=str[b]-'0';
				kx[field[b][a]]=b;
				ky[field[b][a]]=a;
			}
		}
	}
	for(a=1;a<=n;a++){
		if(a==1)ans+=bfs(sx,sy,a);
		if(a>1)ans+=bfs(kx[a-1],ky[a-1],a);
	}
	printf("%d\n",ans);
	return 0;
}

C++: #include <iostream>
#include <queue>
#include <cctype>
#include <stdio.h>
#include <stdlib.h>
#include <map>

#define p(s) puts("s")

using namespace std;
//from は残りのチーズ数
int bfs(int from);
//訪れたら1
typedef pair<int, int> P;
char atlas[1000][1000] = {0};

int h, w, n;
//int start_i , start_j;
int dj[] = {0,1,0,-1 };
int di[] = {-1,0,1,0 };

int main(int argc, char const* argv[])
{
    //行数 一行の長さ 工場の数
    cin >> h >> w >> n;
    //atlas配列初期化&start位置取得
    for (int i = 0; i < h; i++) 
    {
        for (int j = 0; j < w; j++) 
        {
            cin >> atlas[i][j];
            //if (atlas[i][j]== 'S') 
            //{
            //    P start = pair<int, int>(i, j);
            //}
        }
    }

    int sum = 0;
    for(int i=0; i<n; i++)
    {
        //cout << "--------------------------------------------------" << endl;
        //cout << "call bfs(" << i << ")" << endl;
        sum += bfs(i);
        //cout << "bfs(" << i << ")  = " << bfs(i) << endl;
    }
    cout << sum << endl;
    return 0;
}



//チーズsからs+1までの最短経路を返す関数
//start_indexを渡さないと行けない
int bfs(int s)
{
    //cout << "enter bfs(" << s << ")"  << endl;


    //スタートを取得
    P start;
    for(int i=0; i<h; i++)
    {
        for(int j=0; j < w; j++)
        {
            if (s == 0 && atlas[i][j] == 'S' )          { start = P(i,j);} //cout<< "start = "<<  i << ", " <<j <<endl; }
            else if (s != 0 && atlas[i][j] == '0' + s)  { start = P(i,j);} //cout<< "start = "<<  i << ", " <<j <<endl; }
        }
    }

    //is_visit初期化
    int is_visit[1000][1000] = {0};
    queue<P> q;
    map<P, int> dis;

    //一つ入れる
    q.push(start);
    dis[start] = 0;

    while( q.size() )
    {
        //一つ取り出す
        P now = q.front(); q.pop();

        //終了判定
        if(atlas[now.first][now.second] == '0'+s+1)  {
            //cout << "end of bfs(" << s << ")" << "now = (" << now.first <<" ,"<<now.second <<")"<< endl; 
            return dis[now];
        }

        //分岐
        for(int i=0; i < 4; i++)
        {
            P next = P(now.first + di[i], now.second + dj[i]);
            // 訪れてないか　枠の中か 障害物は無いか
            if( next.first < h &&
                next.second < w && 
                dis.find(next) == dis.end() &&
                atlas[next.first][next.second] != 'X'
                )
            {
                q.push(next);
                dis[next] = dis[now] + 1;
            }
        }
    }
}