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 <list>
#include <queue>
#include <stack>
#include <cmath>
#include <ctype.h>
#include <ctime>
#include <cstdio>
#include <vector>
#include <string>
#include <bitset>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <utility>
#include <numeric>
#include <complex>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <cassert>
#include <iostream>
#include <iterator>
#include <algorithm>

using namespace std;

#define REP(i, x, n) for(int i = x; i < n; i++)
#define rep(i, n) REP(i, 0, n)
#define lengthof(x) (sizeof(x) / sizeof(*(x)))
#define FILL(ptr, value) FILL_((ptr), sizeof(ptr)/sizeof(value), (value))
template <typename T>
void FILL_(void * ptr, size_t size, T value){
  std::fill((T*)ptr, (T*)ptr+size, value);
}
//4方向ベクトル→↑←↓
const int dx[] ={1,0,-1,0};
const int dy[] ={0,-1,0,1};
typedef pair<int,int> P;
const int INF =1e+9;
int H,W,N;
int d[1010][1010];
char board[1010][1010];
int sx,sy;
int gx,gy;
int ans;
void bfs(int y,int x,int k){
  for(int i = 1;i <=H;i++){
    for(int j = 1;j <=W;j++){
      d[i][j] =INF;
      if(board[i][j] == k+'0'){
	gx = j;
	gy = i;
      }
    }
  }
  d[y][x] = 0;
  queue<P> que;
  que.push(P(y,x));
  while(!que.empty()){
    P p = que.front();
    que.pop();

    if(p.first ==gy&&p.second ==gx)
      break;
    for(int i = 0;i < 4;i++){
      int nx = p.second+dx[i];
      int ny = p.first+dy[i];
      if(nx >=1&&nx <=W&&ny >=1&&ny <=H&&board[ny][nx] !='X'&&d[ny][nx] ==INF){
	que.push(P(ny,nx));
	d[ny][nx] =d[p.first][p.second]+1;
      }
    }
  }
  ans += d[gy][gx];
  if(k !=N)
    bfs(gy,gx,k+1);
}

int main()
{
  cin>>H>>W>>N;
  for(int i = 1;i <=H;i++){
    for(int j = 1;j <=W;j++){
      cin>>board[i][j];
    }
  }
  for(int i = 1;i <=H;i++){
    for(int j = 1;j <=W;j++){
      if(board[i][j] =='S'){
	sx = j;
	sy = i;
      }
    }
  }
  bfs(sy,sx,1);
  cout <<ans<<endl;
  return 0;
}

C++: #include <iostream>
#include<queue>
using namespace std;
int H,W,N,sx,sy;
char map[1001][1001];
int dir[4][2]={{-1,0},{0,1},{1,0},{0,-1}};
struct Point
{
    int x,y,num,energy,step;
} ;
int BFS()
{
    int ans=1000000;
    queue<Point> q;
    Point p1,p2;
    p1.x=sx;p1.y=sy;p1.num=0;p1.energy=1;p1.step=0;
    q.push(p1);
    while(!q.empty())
    {
       p1=q.front();
       q.pop();
       cout<<p1.x<<" "<<p1.y<<" "<<p1.num<<" "<<p1.step<<" "<<p1.energy<<endl;
       if(p1.num==N&&ans>p1.step)
       {
           ans=p1.step;
           break;
       }

       for(int i=0;i<4;i++)
       {
         p2.x=p1.x+dir[i][0];
         p2.y=p1.y+dir[i][1];
         p2.num=p1.num;
         p2.energy=p1.energy;
         p2.step=p1.step+1;
         if(p2.x<0||p2.x>=H||p2.y<0||p2.y>=W)continue;
         if(map[p2.x][p2.y]=='X') continue;
         else if(map[p2.x][p2.y]=='.')
            {
                q.push(p2);
               // cout<<p2.x<<" "<<p2.y<<endl;
            }
         else if(p2.energy>=(map[p2.x][p2.y]-48))
         {
             p2.num++;p2.energy++;
             map[p2.x][p2.y]='.';
             q.push(p2);
            // cout<<p2.x<<" "<<p2.y<<endl;
         }
       }
    }
return ans;
}
int main()
{
    while(cin>>H>>W>>N)
   {
    for(int i=0;i<H;i++)
     for(int j=0;j<W;j++)
     {
         cin>>map[i][j];
         if(map[i][j]=='S')
         {
             sx=i;sy=j;
         }
     }
    cout<<BFS()<<endl;
  }
}

C++: #include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<cctype>
using namespace std;
int d[1025][1025][10];
struct node
{
    int ti;
    int r, c, time;
    node(int ti = 1, int r = 0, int c = 0, int time = 0) : ti(ti),r(r),c(c),time(time){}
};
int m,n,ying;
char a[1025][1025];
int used[1025];
const int dx[4] = {0,0,1,-1};
const int dy[4] = {1,-1,0,0};
bool is_walk(int r, int c)
{
    return r >= 0 && r < m && c >= 0 && c < n && a[r][c] != 'X';
}
int bfs(int r, int c)
{
    d[r][c][1] = 0;
    queue<node> q;
    q.push(node(1,r,c,0));
    while(q.size()){
        node m = q.front(); q.pop();
        if(a[m.r][m.c] - '0' == ying && used[ying]) return m.time;
        for(int i = 0; i < 4; i++){
            int x = m.r + dx[i], y = m.c + dy[i], ti = m.ti,time = m.time;
            if(!is_walk(x,y) || !d[x][y][ti]) continue;
            d[x][y][ti] = 0;
            if(isdigit(a[x][y])){
                if(a[x][y] - '0' == ti)
                  ti++ , used[a[x][y]-'0']++;
            }
            q.push(node(ti,x,y,time+1));
        }
    }
    return -1;
}
int solve()
{
    memset(d,-1,sizeof(d));
    memset(used,0,sizeof(used));
    for(int i = 0; i < m; i++)
        for(int j = 0; j < n; j++)
            if(a[i][j] == 'S'){
                return bfs(i,j);
            }
}
int main()
{
    while(scanf("%d%d%d",&m,&n,&ying) == 3){
        for(int i = 0; i < m; i++)
            scanf("%s",a[i]);
        printf("%d\n",solve());
    }
    return 0;
}

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


struct ST {
	int x;
	int y;
	int c;
};

char map[1000 + 10][1000 + 10];

bool wen[1000 + 10][1000 + 10] = { 0 };

int main()
{
	int ly, lx, n;

	ST m, tm;

	queue<ST> qu;

	int gy[] = {1,0,-1,0};
	int gx[] = {0,1,0,-1};

	char G[10 + 5] = { '0','1','2','3','4','5','6','7','8','9' };

	int sum = 0;
	int sy, sx;
	int i, j;

	cin >> ly >> lx >> n;

	for (i = 1; i <= ly; i++)
	{
		cin >> map[i] + 1;

		map[i][0] = 'X';
		map[i][lx + 1] = 'X';

		for (j = 1; j <= lx; j++)
		{
			if (map[i][j] == 'S')
			{
				sy = i;
				sx = j;
			}
		}
	}
	for (i = 0; i <= lx + 1; i++)
	{
		map[0][i] = 'X';
		map[ly + 1][i] = 'X';
	}

	m.y = sy;
	m.x = sx;
	m.c = 0;

	qu.push(m);

	for (i = 1; i <= n; i++)
	{
		while (!qu.empty())
		{
			m = qu.front();

			qu.pop();

			if (wen[m.y][m.x])
			{
				continue;
			}
			wen[m.y][m.x] = true;

			if (map[m.y][m.x] == G[i])
			{
				sy = m.y;
				sx = m.x;
				sum += m.c;

				while (!qu.empty())
				{
					qu.pop();
				}
				memset(wen, 0, sizeof(wen));

				m.c = 0;

				qu.push(m);

				break;
			}

			for (j = 0; j < 4; j++)
			{
				tm.y = m.y + gy[j];
				tm.x = m.x + gx[j];
				tm.c = m.c + 1;

				if (map[tm.y][tm.x] != 'X' && !wen[tm.y][tm.x] )
				{
					qu.push(tm);
				}
			}
		}
	}

	cout << sum << endl;

	return 0;
}