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<bits/stdc++.h>
#include<ctype.h>
#define int long long int
#define rep(a,b) for(int a=0;a<b;a++)
#define INF 1000006
using namespace std;

int tx[] = {1,0,-1,0};
int ty[] = {0,1,0,-1};
int w,h,che,sx,sy;
char bases;
int base[1003][1003],base2[1003][1003];

int chee(int x,int y,int n){
    int ans=INF;
    if(base[x][y]==n)return 0;
    if(base[x][y]>=0){
        base[x][y]=-1;
        for(int i=0;i<4;i++){
            if(x+tx[i]>=0&&x+tx[i]<w&&y+ty[i]>=0&&y+ty[i]<h){
                ans = min(ans,chee(x+tx[i],y+ty[i],n)+1);
            }
        }base[x][y]=0;
    }return ans;
}
void sho(int b[1003][1003],int a[1003][1003]){
    rep(i,1003){
        rep(j,1003){
            b[i][j]=a[i][j];
        }
    }
}

signed main(){
    int zx[20],zy[20];
    cin >> h >> w >> che;
    rep(f,h){
        rep(s,w){
            cin >> bases;
            switch(bases){
                case 'S':sx=s;sy=f;
                case '.':base[s][f]=0;
                break;
                case 'X':base[s][f]=-1;
                break;
                default:{base[s][f]=bases - '0';
                        zx[base[s][f]]=s;
                        zy[base[s][f]]=f;
                        }

            }
        }
    }
    sho(base2,base);
    int ans=0;
    ans+=chee(sx,sy,1);
    for(int i=2;i<=che;i++){
        sho(base,base2);
        ans+=chee(zx[i-1],zy[i-1],i);
    }
    cout << ans << endl;
return 0;
}

C++: #include <iostream>
#include <queue>

using namespace std;

int w, h, N;
char grid[1000][1000];
int dist[1000][1000];

bool viable(int i, int j);
void wipe();

int main()
{
    int x, y;
    int tx, ty;
    int choice[4][2]={{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    queue<int> qx, qy;
    char target = '1';
    int res = 0;

    cin >> w >> h >> N;
    for(int i=0; i<w; i++)
    {
        for(int j=0; j<h; j++)
        {
            cin >> grid[i][j];
            if(grid[i][j]=='S')
            {
                x=i;
                y=j;
            }
        }
    }

    while(target-'0'<=N)
    {
        wipe();
        queue<int>().swap(qx);qx.push(x);
        queue<int>().swap(qy);qy.push(y);
        dist[x][y] = 0;
        while(!qx.empty())
        {
            x = qx.front();qx.pop();
            y = qy.front();qy.pop();
            if(grid[x][y]==target)
            {
                res += dist[x][y];
                break;
            }
            for(int i=0; i<4; i++)
            {
                tx = x + choice[i][0];
                ty = y + choice[i][1];
                if(viable(tx, ty))
                {
                    dist[tx][ty] = dist[x][y] + 1;
                    qx.push(tx);
                    qy.push(ty);
                }
            }
        }
        target += 1;
    }
    cout << res << endl;
    return 0;
}

void wipe()
{
    for(int i=0;i<w;i++)
    {
        for(int j=0;j<h;j++)
        {
            dist[i][j]=-1;
        }
    }
}
bool viable(int i, int j)
{
    return 0<=i && i<=w && 0<=j && j<=h && grid[i][j]!='X' && dist[i][j]==-1;
}

C++: #include<iostream>
#include<queue>
#include<climits>
#include<cstdlib>
using namespace std;
int d[1000][1000];
char input[1000][1000];
bool visited[1000][1000];
int H,W,N,S_x,S_y,answer=0;
const int dirx[]={0,-1,0,1};
const int diry[]={1,0,-1,0};
int now='1';
int D[10];
queue<char> q;
void BFS();
void clean();
int main(){
	int i,j;
	char ch; 
	cin>>H>>W>>N;
	for(i=0;i<H*W;i++){
		cin>>ch;
		input[i%W][i/W]=ch;
		d[i%W][i/W]=0;
		if(ch=='S'){
			S_x=i%W;S_y=i/W;
		}
	}
	while(now<=N+48){
		BFS();
		now++;
	}
	for(i=1;i<=N;i++)
		answer+=D[i];
	cout<<answer;
}
void BFS(){
	int x,y,k,mx,my;
	q.push(S_x);
	q.push(S_y);
	visited[S_x][S_y]=true;
	while(!q.empty()){
		x=q.front();q.pop();
		y=q.front();q.pop();
		for(k=0;k<4;k++){
			mx=x+dirx[k];
			my=y+diry[k];
			if(mx<W&&mx>=0&&my<H&&my>=0){ 
			if(input[mx][my]!='X'&&!visited[mx][my]){
				q.push(mx);
				q.push(my);
				d[mx][my]=d[x][y]+1;
				if(input[mx][my]==(char)now){S_x=mx;S_y=my;D[now-48]=d[mx][my];}
				visited[mx][my]=true;
			}}	 
		}
	}
	clean();
}
void clean(){
	int i,j;
	for(i=0;i<=W;i++)
		for(j=0;j<=H;j++){
			visited[i][j]=false;
			d[i][j]=0;}
}

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

struct mouse{
	int y, x, dis;
	mouse(){
		y = x = dis = 0;
	}
};

char stage[1000][1000];
int ng[1000][1000] = {};
int main(){
	int h, w, n;
	mouse s;
	cin >> h >> w >> n;
	for (int i = 0; i < h; i++){
		cin >> stage[i];
		for (int j = 0; j < w; j++){
			if (stage[i][j] == 'S'){
				s.y = i;
				s.x = j;
			}
			else if (stage[i][j] != 'X' && stage[i][j] != '.'){
				stage[i][j] -= '0';
			}
		}
	}

	int ny, nx;
	int situ_y[4] = { -1, 0, 1, 0 }, situ_x[4] = { 0, 1, 0, -1 };
	for (int target = 1; target <= n; target++){
		queue<mouse> mickey;
		mouse m_c;
		for (int i = 0; i < h; i++)for (int j = 0; j < w; j++)ng[i][j] = 0;
		mickey.push(s);
		while (1){
			m_c = mickey.front();
			if (stage[m_c.y][m_c.x] == target){
				s = m_c;
				break;
			}
			if ((m_c.dis != 0 && ng[m_c.y][m_c.x] >= 4)
				|| stage[m_c.y][m_c.x] == 'X'){
				mickey.pop();
				continue;
			}
			ng[m_c.y][m_c.x]++;
			for (int i = 0; i < 4; i++){
				m_c = mickey.front();
				ny = m_c.y + situ_y[i];
				nx = m_c.x + situ_x[i];
				if (ny < 0 || h <= ny || nx < 0 || w <= nx) continue;
				m_c.y = ny;
				m_c.x = nx;
				m_c.dis++;
				mickey.push(m_c);
			}
			mickey.pop();
		}
	}
	printf("%d\n", s.dis);
	return 0;
}

C++: #include<iostream>
#include<queue>
using namespace std;
int G[1005][1005], dist[1005][1005], H, W, K, sx[11], sy[11];
int solve(int ax, int ay, int bx, int by) {
	for (int i = 0; i < 1005 * 1005; i++)dist[i / 1005][i % 1005] = 1000000000;
	queue<pair<int, int>>Q; Q.push(make_pair(ax, ay)); dist[ax][ay] = 0;
	while (!Q.empty()) {
		int a1 = Q.front().first, a2 = Q.front().second; Q.pop();
		int dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 };
		for (int i = 0; i < 4; i++) {
			if (G[a1 + dx[i]][a2 + dy[i]] == 0 && dist[a1 + dx[i]][a2 + dy[i]] > dist[a1][a2] + 1) {
				dist[a1 + dx[i]][a2 + dy[i]] = dist[a1][a2] + 1;
				Q.push(make_pair(a1 + dx[i], a2 + dy[i]));
			}
		}
	}
	return dist[bx][by];
}
int main() {
	cin >> H >> W >> K;
	for (int i = 0; i <= H + 1; i++) {
		for (int j = 0; j <= W + 1; j++) {
			if (i == 0 || i == H + 1 || j == 0 || j == W + 1)G[i][j] = 1;
		}
	}
	for (int i = 1; i <= H; i++) {
		for (int j = 1; j <= W; j++) {
			char p; cin >> p;
			if (p == 'S') { sx[0] = i; sy[0] = j; }
			if (p >= '0' && p <= '9') { sx[p - '0'] = i; sy[p - '0'] = j; }
			if (p == 'X')G[i][j] = 1;
		}
	}
	int cnt = 0;
	for (int i = 0; i < K; i++) {
		cnt += solve(sx[i], sy[i], sx[i + 1], sy[i + 1]);
	}
	cout << cnt << endl;
	return 0;
}