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

typedef pair<int, int> Point;
int h, w, n;
string grid[1001];

int bfs(int sx, int sy, int gx, int gy){
    cout<<"(sx, sy) = "<<"("<<sx<<","<<sy<<")"<<endl;
    bool visited[1001][1001] = {false};
    int dx[4] = {1, 0, -1, 0};
    int dy[4] = {0, 1, 0, -1};

    visited[sy][sx] = true;

    queue<pair<Point, int> > que;
    pair<Point, int> state;
    que.push(make_pair(Point(sx, sy), 0));
    while (1){
        state = que.front();
        que.pop();

        if (state.first.first == gx && state.first.second == gy){
            return state.second;
        }

        for (int i = 0; i < 4; i++){
            int nx = state.first.first + dx[i];
            int ny = state.first.second + dy[i];
            if (0 <= nx && nx < w && 0 <= ny && ny < h 
                && grid[ny][nx] != 'X' && visited[ny][nx] == false){
                visited[ny][nx] = true;
                que.push(make_pair(Point(nx, ny), state.second + 1));
            }
        }
    }
}

int main(int argc, char const *argv[]){
    int sx, sy, gx, gy;
    int ans = 0;
    cin>>h>>w>>n;
    for (int i = 0; i < h; i++){
        cin>>grid[i];
    }

    for (int i = 0; i < h; i++){
        for (int j = 0; j < w; j++){
            if (grid[i][j] == 'S'){
                sx = j; sy = i;
            }
            if (grid[i][j] == '1'){
                gx = j; gy = i;
            }
        }
    }

    for (int size = 2; size-1 <= n; size++){
        ans += bfs(sx, sy, gx, gy);

        sx = gx; sy = gy;
        for (int i = 0; i < h; i++){
            for (int j = 0; j < w; j++){
                if (grid[i][j] - '0' == size){
                    gx = j; gy = i;
                }
            }
        }
    }

    cout<<ans<<endl;

    return 0;
}

C++: #include<cstdio>
#include<iostream>
#include<string>
using namespace std;
int flg[1000][1000],que[1000000][3];
char str[1000][1001]; 
int main(void){
	int i,j,k;
	int x,y,xx,yy,h,w,n,tai,p1,p2;
	int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
	int min,max=1000000;
	cin>>h>>w>>n;
	for(i=0;i<=h;i++){
		for(j=0;j<=w;j++) flg[i][j]=1;
	}
	for(i=0;i<h;i++) cin>>str[i];
	for(i=0;i<h;i++){
		for(j=0;j<w;j++){
			if(str[i][j]=='S'){
				que[0][0]=i; que[0][1]=j; que[0][2]=0;
				flg[i][j]==0;
			}
		}	
	}
	tai=1; p1=0; p2=0;
	for(i=1;i<=n;i++){
		//cout<<i<<endl;
		if(p2>max) break;
		while(1){
			y=que[p1][0]; x=que[p1][1];
			if(str[y][x]-'0'==tai){
				tai++;
		//		printf("aaaaaaaa\n");
				for(j=0;j<h;j++){
					for(k=0;k<w;k++) flg[j][k]=max;
				}
				flg[y][x]==0;
				que[0][0]=y; que[0][1]=x; que[0][2]=que[p1][2];
				p1=0; p2=0;
				break;
			}
			for(j=0;j<4;j++){
				yy=y+dy[j]; xx=x+dx[j];
				if(yy>=0&&xx>=0&&yy<h&&xx<w&&str[yy][xx]!='X'&&flg[yy][xx]!=0){
					p2++;
					que[p2][0]=yy; que[p2][1]=xx; que[p2][2]=que[p1][2]+1;
					flg[yy][xx]=0;
				}
			}
			p1++;
			//printf("%d %d\n",p1,p2);
		}
		min=que[p1][2];
	}
	cout<<min<<endl;
	return 0;
}

C++: #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <cstring>
#include <sstream>
#include <cassert>
using namespace std;
static const double EPS = 1e-10;
typedef long long ll;
typedef pair<int,int> PI;
#define rep(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
int dx[]={0,1,0,-1},dy[]={1,0,-1,0};

typedef struct{
  short x,y;
  int cost;
  short ch;
}mouse;


mouse t;
short cx,cy,nx,ny,ch,nch,h,w,n;
int cost;

main(){
  scanf("%d%d%d",&h,&w,&n);
  short maxch[h][w];
  char ku[h][w];
  
  rep(i,h)scanf("%s",ku[i]);


  rep(i,h)rep(j,w){
    if(ku[i][j]=='S')cx=i,cy=j;
    maxch[i][j]=-1;
  }

  queue<mouse> Q;

  Q.push((mouse){cx,cy,0,0});
  maxch[cx][cy]=0;

  while(!Q.empty()){
    //cout<<Q.size()<<endl;
    t=Q.front();Q.pop();
    cx=t.x,cy=t.y,cost=t.cost;
    ch=t.ch;

    rep(i,4){
      nx=cx+dx[i],ny=cy+dy[i];
      if(nx<0 || nx>=h || ny<0 || ny>=w || ku[nx][ny]=='X')continue;
	 nch=ch;
	 if(ku[nx][ny]<='9' && ku[nx][ny]>='1' && ku[nx][ny]-'0'==t.ch+1){
	   nch=ch+1;
	 }

	 if(maxch[nx][ny]>=nch)continue;
	 if(nch==n){
	   printf("%d\n",cost+1);
	   return 0;
	 }
	 maxch[nx][ny]=nch;
	 Q.push((mouse){nx,ny,cost+1,nch});
    }
  }
}

C++: #include<iostream>
#include<utility>
#include<vector>

using namespace std;

int H, W, N;
char mapT[1000][1000];
char temp_map[1000][1000];

int temp_x = 0, temp_y;
char temp;
int min_rou = 0;
int min_route = 500000;
int final_min_route = 0;
vector<pair<int, int> > dir;

void findSmallRoute(int x, int y, char &factory) {
	if (mapT[x][y] == factory) {
		++min_rou;
		if (min_route > (min_rou-1)) {
			min_route = min_rou - 1;
			temp_x = x;
			temp_y = y;
		}
		--min_rou;
		return;
	}
	if (x < 0 || y >= W || x >= H || y < 0 || mapT[x][y] == 'X') {
		return;
	}
	++min_rou;
	mapT[x][y] = 'X';
	for (vector<pair<int, int> >::iterator it = dir.begin(); it != dir.end(); ++it) {
		findSmallRoute(x + it->first, y + it->second, factory);
		
	}
	mapT[x][y] = temp_map[x][y];
	--min_rou;
	return;
}

int main() {
	dir.push_back({ -1,0 });
	dir.push_back({ 0,1 });
	dir.push_back({ 1,0 });
	dir.push_back({ 0,-1 });
	int start_X = 0, start_Y = 0;
	cin >> H >> W >> N;
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; ++j) {
			cin >> temp;
			mapT[i][j] = temp;
			if (temp == 'S') {
				start_X = i;
				start_Y = j;
			}
		}
	}

	for (int i = 0; i < H; ++i) {
		for (int j = 0; j < W; ++j) {
			temp_map[i][j] = mapT[i][j];
		}
	}

	for (int factory = 1; factory != N + 1; ++factory) {
		
		char n = factory + '0';
		findSmallRoute(start_X, start_Y, n);
		for (int i = 0; i < H; ++i) {
			for (int j = 0; j < W; ++j) {
				mapT[i][j] = temp_map[i][j];
			}
		}
		final_min_route += min_route;
		min_rou = 0;
		min_route = 500000;
		
		start_X = temp_x;
		start_Y = temp_y;
	}

	cout << final_min_route << endl;
	//system("pause");
	return 0;
}