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 <cstdio>
#include <queue>
#include <cstring>
using namespace std;
int H,W,N;
typedef pair<int,int> P;
#define INF 1e-9
const int MAX_N=1001;
char maze[MAX_N][MAX_N];
bool vis[MAX_N][MAX_N];
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};
int d[MAX_N][MAX_N];
bool right(int x,int y)
{
    if(x>=0&&x<H&&y>=0&&y<W&&maze[x][y]!='X'&&!vis[x][y])
        return true;
    return false;
}
int bfs(int sx,int sy,int gx,int gy)
{
    queue<P> que;
    for(int i=0;i<H;i++)
    {
        for(int j=0;j<W;j++)
            d[i][j]=INF;
    }
    que.push(P(sx,sy));
    d[sx][sy]=0;
    while(que.size())
    {
        P p=que.front();que.pop();
        if(p.first==gx&&p.second==gy)
            break;
        for(int i=0;i<4;i++)
        {
            int nx=p.first+dx[i],ny=p.second+dy[i];
            if(right(nx,ny))
            {
                que.push(P(nx,ny));
                d[nx][ny]=d[p.first][p.second]+1;
            }
        }
    }
    return d[gx][gy];
}
int main()
{
    while(scanf("%d%d%d",&H,&W,&N)!=EOF)
    {
        getchar();
        for(int i=0;i<H;i++)
            scanf("%s",maze[i]);
        int ans=0;
        int sx=-1,sy=-1;
        for(int i=0;i<H;i++)
        {
            for(int j=0;j<W;j++)
                if(maze[i][j]=='S')
                {
                    sx=i;sy=j;
                }
            if(sx!=-1&&sy!=-1)
                break;
        }
        for(int i=1;i<=N;i++)
        {
            memset(vis,false,sizeof(vis));
            int nx=-1,ny=-1;
            for(int j=0;j<H;j++)
            {
                for(int k=0;k<W;k++)
                {
                    if(maze[j][k]=='0'+i)
                    {
                        nx=j;ny=k;
                        break;
                    }
                }
                if(nx!=-1&&ny!=-1)
                    break;
            }
            ans+=bfs(sx,sy,nx,ny);
            sx=nx;
            sy=ny;
        }
        printf("%d\n",ans);
    }
    return 0;
}

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

char ma[1001][1001];
bool visited[1001][1001];
int h,w,n;
int dx[4]={-1,0,1,0};
int dy[4]={0,-1,0,1};
int sx,sy;
vector<pair<int,int> >vec(10);

int bfs(int x,int y,int d){
    if(ma[y][x]-'0'==d){
        return 0;
    }
    visited[y][x]=1;
    int ret=100000000;
    for(int i=0;i<4;i++){
        int nx=x+dx[i];
        int ny=y+dy[i];
        if(nx>=0&&nx<w&&ny>=0&&ny<h&&ma[ny][nx]!='X'&&!visited[ny][nx]){
            ret=min(ret,bfs(nx,ny,d));
        }
    }
    visited[y][x]=0;
    return ret+1;
}

int main(){
    memset(visited,0,sizeof(visited));
    cin>>h>>w>>n;
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            cin>>ma[i][j];
            if(ma[i][j]>'0'&&ma[i][j]<='9'){
                vec[ma[i][j]-'0']=make_pair(i, j);
            }
            if(ma[i][j]=='S'){
                vec[0]=make_pair(i, j);
            }
        }
    }
    int c=0;
    for(int i=1;i<=n;i++){
        c+=bfs(vec[i-1].second,vec[i-1].first,i);
    }
    cout<<c<<endl;
}

C++: #include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
struct node
{
	int x,y;
	int d;
	node(int a,int b,int c)
	:x(a),y(b),d(c){}
};
int m,n,p;
char w[1005][1005];
int res;
int dx[]={0,0,1,-1},dy[]={1,-1,0,0};
void bfs(int x,int y)
{
	queue<node> que;
	que.push(node(x,y,0));
	for(int i=1;i<=p;i++)
	{
		while(!que.empty())
		{
			node q=que.front();
			que.pop();
			if(w[q.x][q.y]-'0'==i)
			{
				res+=q.d;
				while(!que.empty())
					que.pop();
				que.push(node(q.x,q.y,0));
				break;
			}
			for(int j=0;j<4;j++)
			{
				int fx=q.x+dx[j],fy=q.y+dy[j];
				if(fx>=0&fx<m&&fy>=0&&fy<n)
				{
					if(w[fx][fy]!='X')
					{
						que.push(node(fx,fy,q.d+1));
					}
				}
			}
		}
	}
}
int main()
{
	scanf("%d%d%d",&m,&n,&p)

		res=0;
		for(int i=0;i<m;i++)
			scanf("%s",w[i]);
		for(int i=0;i<m;i++)
		{
			for(int j=0;j<n;j++)
			{
				if(w[i][j]=='S')
					bfs(i,j);
			}
		}
		printf("%d\n",res);
	return 0;
}

C++: #include <cstdio>
#include <queue>
#define MAX 1000
#define INF 100000

using namespace std;

struct Node {
    int x, y;
};
const int dir[4][2] = {
    {1, 0}, {-1, 0}, {0, 1}, {0, -1}
};
Node start;
char map[MAX + 5][MAX + 5];
int dis[MAX + 5][MAX + 5];
int h, w, n;

int BFS(char cheap);

int main(void)
{
    int step = 0;
    scanf("%d%d%d", &h, &w, &n);
    for (int i = 0; i < h; ++i)
        scanf("%s", map[i]);
    
    for (int i = 0; i < h; ++i)
        for (int j = 0; j < w; ++j)
            if (map[i][j] == 'S') {
                start.x = i;
                start.y = j;
                break;
            }

    for (int i = 1; i <= n; ++i) {
        step += BFS('0' + i);
    }

    printf("%d\n", step);
    return 0;
}

int BFS(char cheap)
{
    for (int i = 0; i < h; ++i)
        for (int j = 0; j < w; ++j)
            dis[i][j] = INF;

    dis[start.x][start.y] = 0;

    Node now, next;
    queue<Node> q;

    q.push(start);

    while (!q.empty()) {
        now = q.front();
        q.pop();

        if (map[now.x][now.y] == cheap) {
            start.x = now.x;
            start.y = now.y;
        } else {
            for (int i = 0; i < 4; ++i) {
                next.x = now.x + dir[i][0];
                next.y = now.y + dir[i][1];

                if (next.x >= 0 && next.x < h &&
                        next.y >= 0 && next.y < w &&
                        map[next.x][next.y] != 'X' &&
                        dis[next.x][next.y] == INF) {
                    dis[next.x][next.y] = dis[now.x][now.y] + 1;
                    q.push(next);
                }
            }
        }
    }

    return dis[start.x][start.y];
}