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

typedef pair<int, int> Pair;
const int INF = 100000000;

int H, W, N;

const int MAX_H = 1000, MAX_W = 1000;
char plant[MAX_H][MAX_W];
int sx, sy;
int dx[4] = {0,1,0,-1}, dy[4] = {1,0,-1,0};
int d[MAX_H][MAX_W];
int mytime;

void bfs() {
    queue<Pair> que;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            d[i][j] = INF;
        }
    }
    char muscle = '1';
    que.push(Pair(sx,sy));
    d[sx][sy] = 0;
    while (que.size()) {
        Pair p  = que.front(); que.pop();
        if (int(muscle)-48-1 == N) break;
        for (int i = 0; i < 4; i++) {
            int nx = p.first + dx[i], ny = p.second + dy[i];
            if (0 <= nx && nx < H && 0 <= ny && ny < W && plant[nx][ny] != 'X' && d[nx][ny] == INF) {
                que.push(Pair(nx, ny));
                d[nx][ny] = d[p.first][p.second] + 1;
            }
            if (muscle == plant[nx][ny]) {
                while(que.size()) {que.pop();}
                que.push(Pair(nx, ny));
                muscle = muscle + 1;
                mytime += d[nx][ny];
                for (int i = 0; i < H; i++) {
                    for (int j = 0; j < W; j++) {
                        d[i][j] = INF;
                    }
                }
                d[nx][ny] = 0;
                break;
            }
        }
    }
}

void solve() {
    mytime = 0;
    bfs();
    printf("%d\n", mytime);
}

int main () {
    //cin >> H >> W >> N;
    scanf("%d%d%d", &H, &W, &N);
    for (int i = 0; i < H; i++) {
        scanf("%s",plant[i]);
        for (int j = 0; j < W; j++) {
            if(plant[i][j] == 'S') {sx = i; sy = j;}
        }
    }
    solve();
}

C++: #include<bits/stdc++.h>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
#define pb push_back
int dy[]={0, 0, 1, -1, 1, 1, -1, -1};
int dx[]={1, -1, 0, 0, 1, -1, -1, 1};

#define FOR(i,a,b) for (int i=(a);i<(b);i++)
#define RFOR(i,a,b) for (int i=(b)-1;i>=(a);i--)
#define REP(i,n) for (int i=0;i<(n);i++)
#define RREP(i,n) for (int i=(n)-1;i>=0;i--)
#define mp make_pair
#define fi first
#define sc second
typedef pair<int,int> P;
typedef pair<P,int> Pp;
int h,w,n;
char s[2000][2000];
bool used[2000][2000];
int bfs(int m){
    REP(i,h)
        REP(j,w)
            used[i][j] = false;
    int sx,sy;char c;
    if(m == 0)
        c = 'S';
    else
        c = m + '0';
    REP(i,h)
        REP(j,w)
            if(c == s[i][j]){sx = i;sy = j;}
    queue<Pp> que;
    REP(i,4){
        int x = sx + dx[i],y = sy + dy[i];
        if((0 <= x && x < h && 0 <= y && y < w) && s[x][y] != 'X' && !used[x][y]){
            if(s[x][y] == m  + 1 + '0')
                return 1;
            que.push(Pp(P(x,y),1));
            used[x][y] = true;
        }
    }
    while(!que.empty()){
        Pp p = que.front();que.pop();

        REP(i,4){
            int x = p.fi.fi + dx[i],y = p.fi.sc + dy[i];
            if((0 <= x && x < h && 0 <= y && y < w) && s[x][y] != 'X' && !used[x][y]){
                if(s[x][y] == m + 1 + '0')
                    return p.sc + 1;
                que.push(Pp(P(x,y),p.sc + 1));
                used[x][y] = true;
            }
        }
    }
    return 1000000000;
}
int main(){
    scanf("%d%d%d",&h,&w,&n);
    REP(i,h)
        scanf("%s",s + i);

    int sum = 0;
    FOR(i,0,n){
        sum += bfs(i);
    }
    printf("%d\n", sum);
    return 0;
}

C++: #include<iostream>
#include<cstring>
#include<queue>
using namespace std ;
struct ST
{
	int x ;
	int y ;
	int cnt = 0 ;
} ;
bool came[ 1000 ][ 1000 ] = {{ 0 }} ;
char map[ 1000 ][ 1000 ] ;
int main()
{
	ST m ,s ;
	queue< ST > que ;
	int n ;
	int w ,h ;
	int kyori = 0 ;
	int mx[ 4 ] = { 0 ,0 ,1 ,-1 } ;
	int my[ 4 ] = { 1 ,-1 ,0 ,0 } ;
	cin >> h >> w >> n ;
	int cheesuu = n ;
	int fx ,fy ;
	char c ;
	bool a = true ;	
	for( int i = 0 ; i < h ; i++ )
	{
		cin >> map[ i ] ;
		for( int j = 0 ; j < w ; j++ && a )
		{
			if( map[ i ][ j ] == 'S' )
			{
				m.x = j ;
				m.y = i ;
				a = false ;
			}
		}
	}
	que.push( m ) ;
	while( n )
	{
		n-- ;
		c = ( cheesuu - n ) + 48 ;
		while( !que.empty() )
		{
			m = que.front() ;
			que.pop() ;
			came[ m.y ][ m.x ] = 1 ;
			if( map[ m.y ][ m.x ] == c )
			{
				kyori += m.cnt ;
				while( ! que.empty() )
				{
					que.pop() ;
				}
				break ;
			}
			for( int i = 0 ; i < 4 ; i++ )
			{
				if( m.x + mx[ i ] > -1 && m.x + mx[ i ] < w && m.y +  my[ i ] > -1 && m.y + my[ i ] < h )
				{
					s = m ;
					s.x += mx[ i ] ;
					s.y += my[ i ] ;
					s.cnt++ ;
					if( map[ s.y ][ s.x ] != 'X' && came[ s.y ][ s.x ] == 0 )
					{
						que.push( s ) ;
					}
				}
			}
		}
		memset( came ,0 ,sizeof( came ) ) ;
		m.cnt = 0 ;
		que.push( m ) ;
	}
	cout << kyori << endl ;
	return 0 ;
}

C++: #include<bits/stdc++.h>
using namespace std;
#define REP(i,n) for(int i=0;i<n;++i)
string s[1010]; //map
int chy[10], chx[10]; //cheese
int d[1010][1010]; //min time
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
int h, w, n, ans;

void bfs(){
  REP(i,n){
    int sy = chy[i], sx = chx[i]; //i.start
    int gy = chy[i+1], gx = chx[i+1]; //i.goal
    queue<int> qy, qx;
    
    qy.push(sy); qx.push(sx);
    REP(j,h) REP(k,w) d[j][k] = 1e9; //init for visit check
    d[sy][sx] = 0; //start time

    while(1){
      int posy = qy.front(); qy.pop();
      int posx = qx.front(); qx.pop();
      if(posy == gy && posx == gx){
        ans += d[gy][gx];
        break;
      }
      REP(j,4){
        int y = posy + dy[j], x = posx + dx[j];
        if(y < 0 || h <= y || x < 0 || w <= x){ //not allowed range
          continue;
        }
        if(d[y][x] == 1e9 && s[y][x] != 'X'){ //first visit && not X
          d[y][x] = d[posy][posx] + 1; //previous time + 1
          qy.push(y); qx.push(x);
        }
      }
    }
  }
}
int main(){
  cin>>h>>w>>n;
  REP(i, h){
    cin>>s[i];
    
    REP(j, w){
      if(s[i][j] == 'S'){
        chy[0] = i;
        chx[0] = j;
      }else if('1' <= s[i][j] && s[i][j] <= '9'){
        chy[s[i][j]-'0'] = i;
        chx[s[i][j]-'0'] = j;
      }
    }
  }    
  bfs();
  cout<<ans<<endl;
  return 0;
}