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<set>
#include<map>
#include<queue>
#include<stack>
#include<bitset>
#include<math.h>
#include<string>
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define pi acos(-1)
#define close ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define open  #ifndef ONLINE_JUDGEfreopen("in.txt","r",stdin);freopen("out.txt","w",stdout); #endif
using namespace std;
typedef long long ll;
const int MAX_N = 1000000+50;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-10;
const ll INF_ll = 0x7fffffffffffffff;
ll mod = 1e9+7;

/*
不要放弃

	Don't give up
*/

inline int read()
{
    int x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9')
    {
        if(ch=='-') f=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9')
    {
        x=10*x+ch-'0';
        ch=getchar();
    }
    return x*f;
}
inline void Out(int a)
{
    if(a>9)
        Out(a/10);
    putchar(a%10+'0');
}

struct Node{
	int x, y, sum, pace;
	int v; 
	//friend bool operator < (Node a,Node b){
	//	return a.pace > b.pace;
	//}
}now,nex;

int H, W, N;
char mapp[1001][1010];
int vis[1001][1010][11];
int sx,sy;
int dirx[4] = {-1,1,0,0};
int diry[4] = {0,0,-1,1};

//priority_queue<Node> q;
queue<Node> q;

void bfs(){
	memset(vis,0,sizeof(vis));
	now.x = sx;
	now.y = sy;
	now.pace = 0;
	now.sum = N;
	now.v = 1;
	vis[sx][sy][1] = 1;
	q.push(now);
	while(!q.empty()){
		//now = q.top();
		now = q.front();
		q.pop();
		//cout<<now.x<<"@@@"<<now.y<<"@@@"<<now.sum<<"####"<<now.v<<endl;
		if(now.sum == 0){
			printf("%d\n",now.pace);
			break;
		}
		int x1,y1;
		for(int i = 0; i < 4; i++){
			x1 = now.x + dirx[i];
			y1 = now.y + diry[i];
			if(x1 >= 1 && x1 <= H && y1 >= 1 && y1 <= W && mapp[x1][y1] != 'X'){
				if(mapp[x1][y1] == '.'){
					if(!vis[x1][y1][now.v]){
						nex.x = x1;
						nex.y = y1;
						nex.pace = now.pace + 1;
						nex.sum = now.sum;
						nex.v = now.v;
						vis[x1][y1][now.v] = 1;
						q.push(nex); 	
					}
				}
				else{
					int num = mapp[x1][y1] - '0';
					nex.x = x1;
					nex.y = y1;
					nex.pace = now.pace + 1;
					if(now.v >= num){
						nex.sum = now.sum - 1;
						nex.v = now.v + 1;
						mapp[x1][y1] = 'X';
						q.push(nex);	
					}
					else{
						nex.sum = now.sum;
						nex.v = now.v;
						q.push(nex);
					}
				}
			}
		}
	}
	return;
}

int main(){
	scanf("%d%d%d",&H,&W,&N);
	for(int i = 1; i <= H; i++){
		getchar();
		for(int j = 1; j <= W; j++){
			scanf("%c",&mapp[i][j]);
			if(mapp[i][j] == 'S'){
				mapp[i][j] == '.';
				sx = i;
				sy = j;
			}
		}
	}
	bfs(); 
 	return 0;
}

/*
                ********
               ************
               ####....#.
             #..###.....##....
             ###.......######              ###            ###
                ...........               #...#          #...#
               ##*#######                 #.#.#          #.#.#
            ####*******######             #.#.#          #.#.#
           ...#***.****.*###....          #...#          #...#
           ....**********##.....           ###            ###
           ....****    *****....
             ####        ####
           ######        ######
##############################################################
#...#......#.##...#......#.##...#......#.##------------------#
###########################################------------------#
#..#....#....##..#....#....##..#....#....#####################
##########################################    #----------#
#.....#......##.....#......##.....#......#    #----------#
##########################################    #----------#
#.#..#....#..##.#..#....#..##.#..#....#..#    #----------#
##########################################    ############
*/

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

typedef pair<int,int> P;

const int inf=10000;
const int maxh=1010;
const int maxw=1010;
const int maxn=9;

int h,w,n;
int d[maxh][maxw];
char m[maxh][maxw];

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

int bfs(char c){
	for(int i=0;i<h;i++){
		fill(d[i],d[i]+w,inf);
	}
	d[bx][by]=0;
	queue<P> que;
	que.push(P(bx,by));
	while(!que.empty()){
		P p=que.front();
		que.pop();
		if(m[p.first][p.second]==c){
			bx=p.first,by=p.second;
			break;
		}
		for(int i=0;i<4;i++){
			int nx=p.first+dx[i];
			int ny=p.second+dy[i];
			if(0<=nx && nx<h && 0<=ny && ny<w && m[nx][ny]!='X' && d[nx][ny]==inf){
				que.push(P(nx,ny));
				d[nx][ny]=d[p.first][p.second]+1;
			}
		}
	}
	return d[bx][by];
}

void solve(){
	for(int i=0;i<h;i++){
		for(int j=0;j<w;j++){
			if(m[i][j]=='S'){
				bx=i,by=j;
				break;
			}
		}
	}
	int ans=0;
	for(int i=1;i<=n;i++){
		ans+=bfs('0'+i);
	}
	cout<<ans<<endl;
}

int main(){
	while(cin>>h>>w>>n){
		for(int i=0;i<h;i++){
			cin>>m[i];
		}
		solve();
	}
	return 0;
}

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

typedef pair<int, int> P;

#define y first
#define x second

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

char map[1024][1024];
P start;
P goal[10];
int h, w, n;

int cheese(P s, int hp);

int main()
{
	scanf("%d %d %d", &h, &w, &n);
	for (int i = 1; i <= h; i++) scanf("%s", &map[i][1]);
	
	for (int i = 1; i <= h; i++){
		for (int j = 1; j <= w; j++){
			if (map[i][j] == 'S') start = P(i, j);
			if ('1' <= map[i][j] && map[i][j] <= '9'){
				goal[map[i][j] - '0'] = P(i, j);
			}
		}
	}
	printf("%d\n", cheese(start, 1));
}

int cheese(P s, int hp)
{
	queue<P> q;
	static int d[1024][1024];
	
	for (int i = 1; i <= h; i++){
		for (int j = 1; j <= w; j++){
			d[i][j] = INF;
		}
	}
	
	q.push(s);
	d[s.y][s.x] = 0;
	while (!q.empty()){
		P p = q.front(); q.pop();
		
		if (p == goal[hp]){
			if (hp == n) return d[p.y][p.x];
			int tmp = d[p.y][p.x];
			return tmp + cheese(p, hp + 1);
		}
		for (int i = 0; i < 4; i++){
			P np(p.y + dy[i], p.x + dx[i]);
			
			if (0 < np.y && np.y <= h && 0 < np.x && np.x <= w && map[np.y][np.x] != 'X' && d[np.y][np.x] == INF){
				q.push(np);
				d[np.y][np.x] = d[p.y][p.x] + 1;
			}
		}
	}
}