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 <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <functional>
#include <array>
#include <stack>
#include <queue>
#include <chrono>
#include <numeric>

#pragma warning(disable:4996)
#define REP(i,n) for(int i = 0 ; i < n ; ++i)
typedef long long Int;

using namespace std;

struct point{
	Int j, i,step;
	point(Int i_, Int j_,Int s) :i(i_), j(j_),step(s){}
};

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

queue<point> que;
char tile[1001][1001];
int H, W;
bool ed[1001][1001];

point solve(char target)
{
	while (!que.empty()){
		point now(que.front());
		ed[now.i][now.j] = true;
		que.pop();
		REP(i, 4){
			int x = now.j + dx[i];
			int y = now.i + dy[i];

			if (x < 0 || y < 0 || x > W || y > H || ed[y][x])
				continue;

			if (tile[y][x] == target){
				return point(y, x,now.step+1);
			}

			if (tile[y][x] != 'X'){
				que.push(point(y, x, now.step + 1));
				ed[y][x] = true;
			}
		}
	}
}

int main()
{
	cin.tie(0); ios::sync_with_stdio(false);
	//fstream fs("input.txt");
	////////////ここから開始///////////
	int n(0);
	cin >> H >> W >> n;

	REP(i, 1001)REP(j, 1001){ tile[i][j] = 'X'; ed[i][j] = false; }

	REP(i, H)REP(j, W)cin >> tile[i][j];

	REP(i, H)REP(j, W){ if (tile[i][j] == 'S')que.emplace(i, j, 0); }

	for (int i = 0; i < n; ++i){
		REP(i_1, H + 1)REP(j_1, W + 1){ ed[i_1][j_1] = false; }
		point t = solve('1' + i);
		que = {};
		que.emplace(t);
		que.front().step
	}

	cout << que.front().step << endl;

	return 0;
}

C++: #include<stack> 
#include<queue> 
#include "StdAfx.h"
const int MAX_H = 1000;
const int MAX_W = 1000;
const int a = 100000000;

using namespace std;

typedef pair<int, int> P;


int H = 0, W = 0, N = 0; 
 
int food[11][2];
char cheese[MAX_H][MAX_W] = {0}; 
int r[MAX_H][MAX_W]; 
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; 

int search(int &sx, int &sy, int &ex, int &ey)
{
 
    P p;
    queue<P> que;
    for(int i=0; i<H; i++)
   {
        for(int j=0; j<W; j++)
       {
           r[i][j] = a;

        }
    }
    que.push(P(sx,sy));
    r[sx][sy] = 0;

    while(que.size())
   {  
        p = que.front();
        que.pop();
        if(p.first == ex && p.second == ey)
			break;
	

	    for(int i=0; i<4; i++)
	   {
		    int xn = p.first + dx[i];
		    int yn = p.second + dy[i];


		    if(xn >= 0 && xn < H && yn >= 0 && yn < W && cheese[xn][yn]!='X' && r[xn][yn] == a )
		   {
			    que.push(P(xn,yn));
			    r[xn][yn] = r[p.first][p.second] + 1;
		    }
	    }

	}
	return r[ex][ey];
}

int main()
{
	int dis = 0;
    cin >> H >> W >> N;
    for(int i=0; i<H; i++)
   {
        for(int j=0; j<W; j++)
       {
          cin >> cheese[i][j];
          if(cheese[i][j] == 'S')
         {
             food[0][0] = i;
             food[0][1] = j;
             cheese[i][j] = '.';
          }
          if(cheese[i][j]>48&&cheese[i][j]<58)
         {
             int num = cheese[i][j] - 48;  
             factor[num][0] = i;
             factor[num][1] = j;
          }
       }
    }
   

    for(int i=0; i<N; i++)
   {
       dis += search(food[i][0], food[i][1], food[i+1][0], food[i+1][1]); 
    }
    
	cout << dis << endl;
    return 0;
}

C++: #include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int n,m,k,step[1010][1010],temp[1010][3];
char a[1010][1010];
int dx[]={-1,1,0,0},dy[]={0,0,-1,1};
bool vis[1010][1010];
typedef pair<int,int> P;
int bfs(int x,int y,int ex,int ey)
{
	memset(vis,true,sizeof(vis));
	memset(step,0,sizeof(step));
	queue <P> que;
	que.push(P(x,y));
	vis[x][y]=false;
	while(!que.empty())
	{
		P tmp=que.front();que.pop();
		int b=que.size();
		if(tmp.first==ex&&tmp.second==ey)
		  return step[tmp.first][tmp.second];
		for(int i=0;i<4;i++)
		{
			int tx=tmp.first+dx[i];
			int ty=tmp.second+dy[i];
			if(tx>0&&tx<=n&&ty>0&&ty<=m&&vis[tx][ty]==true&&a[tx][ty]!='X')
			{
				que.push(P(tx,ty));
				vis[tx][ty]=false;
				step[tx][ty]=step[tmp.first][tmp.second]+1;
			}
		}
	}
}
int main()
{
	ios::sync_with_stdio(false);
	cin>>n>>m>>k;
		int sx,sy;
		for(int i=1;i<=n;i++)
		  for(int j=1;j<=m;j++)
		  {
			cin>>a[i][j];
			if(a[i][j]=='S')
			  sx=i,sy=j;
			//temp[0][0]=i;
			//temp[0][1]=j;
		  }
		a[sx][sy]='0';
		int tot=0,ans=0;
		for(int i=1;i<=k;i++)
		{
			for(int j=1;j<=n;j++)
			  for(int l=1;l<=m;l++)
			    if(a[j][l]=='0'+i)
			    {
			    	tot=bfs(sx,sy,j,l);
			    	sx=j,sy=l;
				}
			ans+=tot;
		}
		cout<<ans<<endl;
	return 0;
}

C++: #pragma GCC optimize(2)
#include <bits/stdc++.h>
using namespace std;
#define P pair<int, int>

char board[1001][1001];
int d[1001][1001];
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};

int main() {
    std::ios::sync_with_stdio(false);
    int h, w, n, sx, sy;
    cin >> h >> w >> n;
    for (int i = 1; i <= h; i++) {
        for (int j = 1; j <= w; j++) {
            cin >> board[i][j];
            if (board[i][j] == 'S') sx = i, sy = j;
        }
    }
    int tar = 1, sum = 0;
    while (tar <= n) {
        queue<P> que;
        que.push(P(sx, sy));
        memset(d, -1, sizeof(d));
        d[sx][sy] = 0;
        while (!que.empty()) {
            P p = que.front();
            if (board[p.first][p.second] == '0' + tar) {
                sx = p.first, sy = p.second;
                sum += d[p.first][p.second];
                //printf("%d %d %d %d\n",p.first,p.second,d[p.first][p.second],sum);
                break;
            }
            que.pop();
            for (int i = 0; i < 4; i++) {
                int nx = p.first + dx[i], ny = p.second + dy[i];
                if (1 <= nx && nx <= h && 1 <= ny && ny <= w &&
                    board[nx][ny] != 'X' && d[nx][ny] == -1) {
                    d[nx][ny] = d[p.first][p.second] + 1;
                    que.push(P(nx, ny));
                }
            }
        }
        tar++;
    }
    printf("%d\n", sum);
}