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>
#include<set>
#include<queue>
#include<string>
#include<cstdio>
#include<stack>
#include<cmath>
#include<bitset>
#include<memory>
#include<memory.h>
#include<utility>
#include<map>
using namespace std;
#define FOR(i,m,n) for(i=m;i<n;i++)
#define CLR(a,b) memset(a,b,sizeof(a))
#define ROF(i,m,n) for(i=m;i>=n;i--)
#define BUG cout<<"debug"<<endl;
#define RT return
#define BK break
#define HEAP priority_queue
#define SP " "
#define rd(x) (rand()%(x))
#define lowf(a,b,c) lower_bound(a,b,c)
#define upf(a,b,c) upper_bound(a,b,c)
#define sh(a) cout<<a<<endl
typedef long long LL;
typedef vector<int> VI;
const int INF = 2147483647;
const int NEN = -INF - 1;
const LL LINF = 9223372036854775807;
int W, H, I1, J1,N;char g[1005][1005];
bool vis[1005][1005];
bool can(int x, int y)
{
	return x >= 0 && y >= 0 && x < H&&y < W&&g[x][y]!='X';
}
typedef struct node
{
	int i, j, sum;
	node()
	{
		;
	}
	node(int a, int b, int c)
	{
		i = a; j = b; sum = c;
	}
}node;
queue<node>bfs;
typedef struct pos
{
	int x,y;
}pos;
pos all[10];
int dir[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };
int main()
{
	cin >> H >> W >> N;
	node temp;
	int T,i,j,ans=0;
	FOR(i, 0, H)
	{
		FOR(j, 0, W)
		{
			//cin >> g[i][j];
			scanf("%c", &g[i][j]);
			if (g[i][j] > '0'&&g[i][j] <='9')
			{
				all[g[i][j] - 48].x = i;
				all[g[i][j] - 48].y = j;
			}
			else if (g[i][j] == 'S')I1 = i, J1 = j;
		}
	}
	FOR(T,0,N)
	{
		CLR(vis, 0);
		while (!bfs.empty())bfs.pop();
		if(T>0)bfs.push(node(all[T].x, all[T].y, 0));
		else bfs.push(node(I1, J1, 0));
		while (!bfs.empty())
		{
			temp = bfs.front();
			bfs.pop();
			if (g[temp.i][temp.j] == T+48+1)
			{
				ans += temp.sum;
				break;
			}
			int k = 4,tx,ty;
			while (k--)
			{
				tx = temp.i + dir[k][0];
				ty = temp.j + dir[k][1];
				if (can(tx, ty) == true&&!vis[tx][ty])
				{
					vis[tx][ty] = 1;
					bfs.push(node(tx, ty, temp.sum + 1));
				}
			}
		}
	}
	cout << ans;
}

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

#define fi first
#define se second
#define x second
#define y first

typedef pair<int,int> pii;

vector<string> in;
int H, W, N;

int search_length(char s, char g) {
	queue<pair<pii, int> > que;
	int vx[] = {1, -1, 0, 0};
	int vy[] = {0, 0, 1, -1};
	for(int i = 0; i < in.size(); i++) {
		for(int j = 0; j < in[i].size(); j++) {
			if(in[i][j] == s) {
				que.push(pair<pii, int>(pii(i, j), 0));
				j = in[i].size();
				i = in.size();
			}
		}
	}
	int visited[1024][1024] = {0};
	int ret;
	while(!que.empty()) {
		pair<pair<int,int>, int> tmp;
		tmp = que.front(); que.pop();
		for(int i = 0; i < 4; i++) {
			int x_, y_;
			x_ = tmp.fi.x + vx[i]; y_ = tmp.fi.y + vy[i];
			if(!(x_ < 0 || in[0].size() <= x_ || y_ < 0 || in.size() <= y_)) {
				if(in[y_][x_] == g) {
					return tmp.se + 1;
				}
				if(!visited[y_][x_] && in[y_][x_] != 'X') {
					visited[y_][x_] = 1;
					que.push(pair<pii,int>(pii(y_, x_), tmp.se + 1));
				}
			}
		}
	}
	cout << "reach" << endl;
	return -1;
}

int main() {
	cin >> H >> W >> N;
	int ret = 0;
	for(int i = 0; i < H; i++) {
		string tmp;
		cin >> tmp;
		in.push_back(tmp);
	}

	for(int i = 0; i < N; i++) {
		ret += search_length(i == 0 ? 'S' : (i + '0'), i + 1 + '0');
	}
	cout << ret << endl;
	return 0;
}

C++: /* AOJ0558 Cheese */

#include <iostream>
#include <cctype>
#include <queue>
#include <string.h>

using namespace std;

const int DIRECTSIZE = 4;
struct _direct {
    int drow;
    int dcol;
} direct[DIRECTSIZE] = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};

const int N = 1000;
const int N2 = 10;
char grid[N][N], visited[N][N];
int h, w, n;
struct _factory {
    int row, col;
} factory[N2+1];

struct _node {
    int row, col, level;
};

int bfs(int n)
{
    _node start, temp;

    start.row = factory[n-1].row;
    start.col = factory[n-1].col;
    start.level = 0;
    visited[start.row][start.col] = 1;

    queue<_node> q;
    q.push(start);

    while(!q.empty()) {
        _node front = q.front();
        q.pop();

        for(int i=0; i<=DIRECTSIZE; i++) {
            int nextrow = front.row + direct[i].drow;
            int nextcol = front.col + direct[i].dcol;
            if( 0 <= nextrow && nextrow < h && 0 <= nextcol && nextcol < w) {
                if(nextrow == factory[n].row && nextcol == factory[n].col) {
                    return front.level + 1;
                } else if(visited[nextrow][nextcol] == 0 && grid[nextrow][nextcol] == '.') {
                    visited[nextrow][nextcol] = 1;
                    temp.row = nextrow;
                    temp.col = nextcol;
                    temp.level = front.level + 1;
                    q.push(temp);
                }
            }
        }
    }

    return 0;
}

int main()
{
    while(cin >> h >> w >> n) {
        for(int i=0; i<h; i++)
            for(int j=0; j<w; j++) {
                cin >> grid[i][j];

                if(grid[i][j] == 'S') {
                    factory[0].row = i;
                    factory[0].col = j;
                    grid[i][j] = '.';
                } else if(isdigit(grid[i][j])) {
                    factory[grid[i][j] - '0'].row = i;
                    factory[grid[i][j] - '0'].col = j;
                    grid[i][j] = '.';
                }
            }

        int minstep = 0;
        for(int i=1; i<=n; i++) {
            memset(visited, 0, sizeof(visited));
            minstep += bfs(i);
        }

        cout << minstep << endl;
    }

    return 0;
}