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>
#include<string>
#include <cstring>
#include<cstdio>
using namespace std;

  int used[1001][1001];
  char m[1001][1001];
  int H,W,N,sx,sy;
  
  const int dx[4]={1,0,-1,0};
  const int dy[4]={0,1,0,-1};

bool check(int x,int y){
  return x>=0&&y>=0&&x<H&&y<W&&m[x][y]!='X';
}

void debug()
{
  for(int i = 0; i < H; i++) {
    for(int j = 0; j < W; j++){
      printf("%3d", used[i][j]);
    }
    puts("");
  }
  puts("");
} 
int bfs(int p){
  memset(used, 0, sizeof used);
  queue<pair<int,int> > que;
  que.push(make_pair(sx,sy));
  while(!que.empty()){
    pair<int,int> pos= que.front();
    que.pop();
    for(int i=0;i<4;i++){
      int x=pos.first+dx[i];
      int y=pos.second+dy[i];
      if(check(x,y) && used[x][y] == 0){
       que.push(make_pair(x,y));
       used[x][y] = used[pos.first][pos.second] + 1;
      }
      if(m[x][y]==p+'0'){
	
       sx=x;
       sy=y;
       return used[x][y];
      }
    }
  }
}



int main()
{
  cin>>H>>W>>N;
  for(int i=0;i<H;i++){
    for(int j=0;j<W;j++){
      cin>>m[i][j];
      if(m[i][j]=='S'){
       sx=i;
       sy=j;
      }	
    }
  }
  int res=0;
  for(int i=1;i<=N;i++){
    res+=bfs(i);
  }
  cout << res << endl;
  
}

C++: #include <algorithm>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <cassert>
#include <iostream>
#include <map>
#include <queue>
#include <sstream>
#include <string>
#include <stack>
#include <set>
#include <vector>

using namespace std;

#define all(c) ((c).begin()), ((c).end())
#define dump(c) cerr << "> " << #c << " = " << (c) << endl;
#define iter(c) __typeof((c).begin())
#define tr(i, c) for (iter(c) i = (c).begin(); i != (c).end(); i++)
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define repi(i, a, b) for (int i = (int)(a); i <= (int)(b); i++)

#define mp make_pair
#define fst first
#define snd second
#define pb push_back

typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<string> vs;
typedef pair<int,int> pii;

const int INF = 1 << 29;
const double EPS = 1e-10;

template<typename T1,typename T2>
ostream& operator<<(ostream& os,const pair<T1,T2>& p){
    return os<<'('<<p.first<<','<<p.second<<')';
}
template<typename T>
ostream& operator<<(ostream& os,const vector<T>& a){
    os<<'[';
    rep(i,a.size()) os<<(i?" ":"")<<a[i];
    return os<<']';
}

typedef pair<int, pair<int, pii> > State;

int H, W, N;
char m[1010][1010];

int main() {
	cin >> H >> W >> N;
	pii start;
	rep(i, H) rep(j, W) {
		cin >> m[i][j];
		if (m[i][j] == 'S') {
			start.fst = j;
			start.snd = i;
		}
	}
	
	priority_queue<State, vector<State>, greater<State> > q;
	q.push(mp(0, mp(0, start)));
	map<pair<int, pii>, bool> visited;
	
	while(!q.empty()) {
		State st = q.top();
		q.pop();
		if (visited[st.snd]) continue;
		visited[st.snd] = true;
		
		int x = st.snd.snd.fst, y = st.snd.snd.snd;
		int ate = st.snd.fst;
		if (__builtin_popcount(ate) == N) {
			cout << st.fst << endl;
			break;
		}
		static const int dx[] = {1, 0, -1, 0};
		static const int dy[] = {0, 1, 0, -1};
		rep(d, 4) {
			int tx = x + dx[d];
			int ty = y + dy[d];
			if (tx < 0 || tx >= W || ty < 0 || ty >= H) continue;
			if (m[ty][tx] == 'X') continue;
			if (isdigit(m[ty][tx])) {
				if (ate & 1 << m[ty][tx] - '0') continue;
				int hp = 1 + __builtin_popcount(ate);
				if (hp >= m[ty][tx] - '0') {
					q.push(mp(st.fst + 1, mp(ate | 1 << m[ty][tx] - '0', mp(tx, ty))));
					continue;
				}
			}
			q.push(mp(st.fst + 1, mp(ate, mp(tx, ty))));
		}
	}
    
    return 0;
}

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

const int INF=0x3f3f3f3f;
int h,w,n;//
typedef pair<int,int> P;
queue <P> q;
char g[1002][1002];
int x,y;//起点的横纵坐标
int nx,ny;//下一个点
int d[1002][1002];
int _x[4]={-1,0,0,1},_y[4]={0,-1,1,0};
bool is_legal(int x,int y)//格子是否越界
{
	if(x>=1&&x<=h&&y>=1&&y<=w) return true;
	else return false;
		
}
//队列初始要有起点
//从起点出发，目的地：power的奶酪
//power奶酪的最小步数
int bfs(int power)
{
	while(!q.empty()) q.pop();
	q.push(P(x,y));
	for(int i=1;i<=h;i++)
			for(int j=1;j<=w;j++)
			{
				d[i][j]=INF;
			}
	d[x][y]=0;
	while(!q.empty())
	{
		P p=q.front();
		q.pop();
		int row=p.first;
		int column=p.second;
		
		for(int i=0;i<4;i++)
		{
			nx=row+_x[i];
			ny=column+_y[i];
			if(!is_legal(nx,ny)) continue;
			
			//d[nx][ny]=d[row][column]+1;障碍物或越界，d数组不变
			if(g[nx][ny]=='0'+power) 
			{
				d[nx][ny]=d[row][column]+1;
				//下一次bfs的起点
				x=nx;
				y=ny;
				return d[nx][ny];
			}
			if(g[nx][ny]!='X') 
			{
				
				if(d[row][column]+1<d[nx][ny])
				{
					d[nx][ny]=d[row][column]+1;
				q.push(P(nx,ny));
				}
				
			}
		}
	}
	return INF;
}

int main()
{
	while(scanf("%d %d %d",&h,&w,&n)!=EOF)
	{
		for(int i=1;i<=h;i++)
			for(int j=1;j<=w;j++)
			{
				cin>>g[i][j];
				if(g[i][j]=='S') {x=i;y=j;}
			}
		
		int ans=0;
		
		
		//1～n奶酪的最小步数之和
		
		for(int k=1;k<=n;k++) {
			ans+=bfs(k);
		}
		
		cout<<ans<<endl;
	}
	return 0;
}