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 <stdio.h>
#include <queue>
#include <utility>
#include <string.h>
using namespace std;
int H,W,N;
#define MAXN 1005
char layout[MAXN][MAXN];
int step[MAXN][MAXN];
queue<pair<int,int> > q;
void getInput() {
    scanf("%d %d %d",&H,&W,&N);
    char c;
    for(int i=0;i<H;i++) {
        c=getc(stdin);
        if(c=='\r') getc(stdin);
        for(int j=0;j<W;j++) {
            c=getc(stdin);
            layout[i][j]=c;
            if(c=='S')
                q.push(make_pair(i,j));
        }
    }
}

void checkInput() {
    for(int i=0;i<H;i++) {
        for(int j=0;j<W;j++) {
            printf("%c",layout[i][j]);
        }
        printf("\n");
    }
}


int bfs(int strength) {
    int totalstep=0;
    while(!q.empty()) {
        pair<int,int> p=q.front();
        q.pop();
        int row=p.first,col=p.second;
        if(layout[row][col]==strength+'0') {
            // printf("%d %d\n",row,col);
            strength++;
            totalstep+=step[row][col];
            // printf("%d\n",totalstep);
            while(!q.empty()) q.pop();
            memset(step,0xff,sizeof(step));
            step[row][col]=0;
            if(strength==N+1) return totalstep;
        }
        // printf("%d %d\n",row,col);
        if(row>0 && layout[row-1][col]!='X' && step[row-1][col]==-1) {
            step[row-1][col]=step[row][col]+1;
            q.push(make_pair(row-1,col));
        }
        if(col>0 && layout[row][col-1]!='X' && step[row][col-1]==-1) {
            step[row][col-1]=step[row][col]+1;
            q.push(make_pair(row,col-1));
        }
        if(row<H-1 && layout[row+1][col]!='X' && step[row+1][col]==-1) {
            step[row+1][col]=step[row][col]+1;
            q.push(make_pair(row+1,col));
        }
        if(col<W-1 && layout[row][col+1]!='X' && step[row][col+1]==-1) {
            step[row][col+1]=step[row][col]+1;
            q.push(make_pair(row,col+1));
        }
    }
}

int main() {
#ifdef debug
    freopen("in.txt","r",stdin);
#endif
    memset(step,0xff,sizeof(step));
    getInput();
    step[q.front().first][q.front().second]=0;
    checkInput();
    int strength=1;
    printf("%d\n",bfs(strength));
}

C++: #include <iostream>
#include <stdio.h>
#include <string>
#include <map>
#include <stack>
#include <vector>
#include <string.h>
#include <set>
#include <queue>
#include <cmath>
#include <algorithm>

using namespace std;

struct node
{
	int x;
	int y;
	int dist;

	node(int x , int y , int dist)
	{
		this -> x = x;
		this -> y = y;
		this -> dist = dist;
	}
};

bool vis[1010][1010];
char input[1010][1010];
int dx[4] = {- 1 , 0 , 1 , 0};
int dy[4] = {0 , 1 , 0 , - 1};
queue<node> q;

bool inArea(int x , int y , int n , int m)
{
	return x >= 0 && x < n && y >= 0 && y < m;
}

int solve(int sx , int sy , int h , int w , int n)
{
	while (!q.empty())
		q.pop();

	int value = 1;
	q.push(node(sx , sy , 0));
	vector<node> prev;

	while (!q.empty())
	{
		node no = q.front();
		q.pop();
		vis[no.x][no.y] = true;

		prev.push_back(node(no.x , no.y , no.dist));

		if (input[no.x][no.y] >= '0' && input[no.x][no.y] <= '9' && ((input[no.x][no.y] - '0') == value))
		{
			value ++;
			if (value == n + 1)
				return no.dist;

			while (!q.empty())
				q.pop();

			for (int i = 0;i < prev.size() - 1;i ++)
				vis[prev[i].x][prev[i].y] = false;
			prev.clear();
		}
		for (int i = 0;i < 4;i ++)
		{
			int tx = no.x + dx[i];
			int ty = no.y + dy[i];
			if (inArea(tx , ty , h , w) && !vis[tx][ty] && input[tx][ty] != 'X')
				q.push(node(tx , ty , no.dist + 1));
		}
	}
	return - 1;
}

int main()
{
	int i , j , h , w , n;
	while (scanf("%d%d%d" , &h , &w , &n) != EOF)
	{
		for (i = 0;i < h;i ++)
			for (j = 0;j < w;j ++)
				vis[i][j] = false;

		int sx , sy;
		for (i = 0;i < h;i ++)
		{
			scanf("%s" , input[i]);
			for (j = 0;j < w;j ++)
			{
				if (input[i][j] == 'S')
				{
					sx = i;
					sy = j;
				}
			}
		}
		// ???S????§????
		printf("%d\n" , solve(sx , sy , h , w , n));

	}
	return 0;
}

C++: // AOJ 0558
#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<queue>
#include<map>
#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define X first
#define Y second
using namespace std;

typedef pair<int,int> P;
typedef pair<int,P> S;

int H, W, N;
const int HMAX = 1008, WMAX = 1008;
char field[HMAX][WMAX];

bool legal(P p) {
  return 0 <= p.X and p.X < W and 0 <= p.Y and p.Y < H
    and field[p.X][p.Y] != 'X';
}

const int INF = 1e7;
int dist[HMAX][WMAX];

int distance(P start, P goal) {
  priority_queue<S, vector<S>, greater<S> > que;
  REP(x,W) REP(y,H) { dist[x][y] = INF; }

  dist[start.X][start.Y] = 0;
  que.push(S(0, start));

  while (!que.empty()) {
    S state = que.top(); que.pop();
    P cur = state.second;
    if (dist[cur.X][cur.Y] < state.first) continue;
    
    const int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
    REP(i, 4) {
      P p = P(cur.X + dx[i], cur.Y + dy[i]);
      if (legal(p) and dist[p.X][p.Y] > dist[cur.X][cur.Y] + 1) {
        dist[p.X][p.Y] = dist[cur.X][cur.Y] + 1;
        que.push(S(dist[p.X][p.Y], p));
      }
    }
  }
  return dist[goal.X][goal.Y];
}

P search(char c) {
  REP(y, H) REP(x, W) {
    if (field[x][y] == c)
      return P(x, y);
  }
}

int solve() {
  int ans = 0;
  P start = search('S');
  for (int i = 1; i <= N; i++) {
    P goal = search('0' + i);
    ans += distance(start, goal);
    start = goal;
  }
  return ans;
}

int main() {
  cin >> H >> W >> N;
  REP(y, H) {
    string row;
    cin >> row;
    REP(x, W) {
      field[x][y] = row[x];
    }
  }

  cout << solve() << endl;
}