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 <stdio.h>

#include <queue>

using namespace std;

char map[1000][1000];
bool visited[1000][1000];
int W, H, N;
int startR, startC;
int targetR[10];
int targetC[10];

int dr[4] = {-1, 1, 0, 0};
int dc[4] = {0, 0, -1, 1};

int getMinTime() {
  int time = 0;
  int curR = startR;
  int curC = startC;
  for (int i = 0; i < N; ++i) {
    memset(visited, false, sizeof(visited));
    queue<int> q;
    q.push((curR << 16) | curC);
    visited[curR][curC] = true;
    while (!visited[targetR[i]][targetC[i]]) {
      time++;
      int count = q.size();
      while (count-- > 0) {
        int node = q.front();
        q.pop();
        int r = node >> 16;
        int c = node & 0xffff;
        for (int j = 0; j < 4; ++j) {
          int nr = r + dr[j];
          int nc = c + dc[j];
          if (nr >= 0 && nr < H && nc >= 0 && nc < W && !visited[nr][nc] && map[nr][nc] != 'X') {
            visited[nr][nc] = true;
            q.push((nr << 16) | nc);
          }
        }
      }
    }
    curR = targetR[i];
    curC = targetC[i];
  }
  return time;
}

int main() {
  //freopen("Cheese.in", "r", stdin);
  while (scanf("%d%d%d", &H, &W, &N) == 3 && W != 0 && H != 0 && N != 0) {
    for (int r = 0; r < H; ++r) {
      for (int c = 0; c < W; ++c) {
        char ch;
        do {
          ch = getchar();
        } while (isspace(ch));
        if (ch == 'S') {
          startR = r;
          startC = c;
        } else if (isdigit(ch)) {
          int index = ch - '0' - 1;
          targetR[index] = r;
          targetC[index] = c;
        }
        map[r][c] = ch;
      }
    }
    int result = getMinTime();
    printf("%d\n", result);
  }
  return 0;
}

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

int h,w,n;
const int MAX_N=1000;
char map[MAX_N][MAX_N];
struct point{
    int x,y;
    int step;
    point(){
        x=0; y=0; step=0;
    }
    point(int xx, int yy, int ss){
        x=xx;
        y=yy;
        step=ss;
    }
};
struct point p[10];

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

int ok(int x, int y){
    if(x>=0 && x<h && y>=0 && y<w) return 1;
    return 0;
}

int bfs(int next){
    int nextcheese = next +1; int res=0;
    
    queue<point> q;
    point cur(p[next].x, p[next].y,0);
    q.push(cur);
    while(q.size()){
        cur = q.front(); q.pop(); 
        int x=cur.x, y=cur.y;
        int nx, ny;
        for(int i=0; i<4; i++){
            nx = x+dx[i]; ny=y+dy[i];
            if(ok(nx, ny)){
                if((map[nx][ny]-'0')==nextcheese) return ++cur.step;
                if(map[nx][ny]=='.'){
                    point temp(nx, ny, cur.step+1);
                    q.push(temp);
                }
            }
        }
    }
}

void solve(){
    int sx, sy;
    scanf("%d%d%d", &h, &w, &n);
    for(int i=0; i<h; i++){
        for(int j=0; j<w; j++){
            char ch;
            cin>>ch; map[i][j]=ch;
            switch(ch){
                case '.': break;
                case 'X': break;
                case 'S': p[0].x = i; p[0].y = j; break;
                default:
                int t=ch-'0';
                p[t].x = i; p[t].y = j;
            }
        }
    }
    int step=0;
    for(int i=0; i<n; i++){
        step+=bfs(i);
    }
    printf("%d\n", step);
}


int main(){
    solve();
}

C++: #include<cstdio.h>
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
struct PP{
	int x;
	int 
	int Z;
	int c;
};
char s[1002][1002],C[11]={"0123456789"};
int D[1002][1002];
int A[1002][1002],d;
int main(){
	PP S;
	queue<PP> P;
	int  w,h;
	int d=0,i=0,j=0,l=-1;
	int x[4]={ 1, 0,-1,0};
	int y[4]={ 0 ,1,0,-1};
	scanf("%d %d %d",&h,&w,&d);
	memset(A,0,sizeof(A));
   memset(D,0,sizeof(D));
		for(i=0;i<h;i++){
		scanf("%s",s[i]);
	}
	for(i=0;i<h;i++){
		for(j=0;j<w;j++){
		if(s[i][j]=='S'){
			S.x=j;
			S.y=i;
			S.Z=0;
			S.c=1;
			P.push(S);
		}
		}
	}
	while(1){
		l++;
		
		if(l==4) {
			l=0;
			P.pop();
		}
		S=P.front();
		A[S.y][S.x]=1;
		S.x+=x[l];
		S.y+=y[l];
		S.Z++;
		if(A[S.y][S.x]==1||s[S.y][S.x]=='X'||S.y==h||S.x==w||S.x==-1||S.y==-1){
		continue;
		}
		if(s[S.y][S.x]=='.'){}
		else{
			if(C[S.c]==s[S.y][S.x]){
				S.c++;
				if(S.c==d+1){
				break;
				}
				while(!P.empty()){
				P.pop();
				
				}
			memset(A,0,sizeof(A));
			l=-1;
			}

		} 
		P.push(S);
	}
	printf("%d\n",S.Z);
	return 0;
}

C++: #include <iostream>
#include <string>
#include <algorithm>
#include <set>
#include <vector>
#include <cstring>
#include <climits>
#include <queue>
using namespace std;

#define REP(i,a,n) for(int i=(a); i<(int)(n); i++)
#define rep(i,n) REP(i,0,n)

const int dx[] = {0, 0, 1,-1};
const int dy[] = {1,-1, 0, 0};
int h,w,n,sx,sy;
char f[1010][1010];
int vt[1010][1010];

int main(){
	int ret = 0;
	scanf("%d%d%d",&h,&w,&n);
	rep(i,h)scanf("%s",f[i]);
	rep(i,h)rep(j,w)if( f[i][j]=='S' ){
		sx = j;  sy = i;
	}
	
	//printf("sx,sy %d,%d\n",sx,sy);
	
	for(int i=1; i<=n; i++){
		bool flag = false;
		queue<pair<int,int> > q;
		memset(vt,-1,sizeof(vt));
		q.push( make_pair(sx,sy) );
		vt[sy][sx] = 0;
		//printf("i:%d , %d\n",i,ret);

		while( !q.empty() && !flag ){
			int x = q.front().first;
			int y = q.front().second;
			int c = vt[y][x];
			q.pop();
			rep(k,4){
				int tx = x + dx[k];
				int ty = y + dy[k];
				//printf("tx,ty %d,%d\n",tx,ty);
				if( tx<0 || ty<0 || tx>=w || ty>=h ||
						vt[ty][tx]!=-1 || f[ty][tx]=='X' ) continue;
				
				if( f[ty][tx]==i+'0' ){
					ret += c+1;
					sy = ty; sx = tx;
					flag = true;
					break;
				}
				vt[ty][tx] = c+1;
				//printf("(%d,%d):%d\n",tx,ty,c+1);
				q.push( make_pair(tx,ty) );
			}
		}
		//if( !flag )puts("eeeeeeeeeeee");
	}
	printf("%d\n",ret);
	
	return 0;
}